WPF Binding - get path to Image from ComboBox

前端 未结 1 559
猫巷女王i
猫巷女王i 2021-01-27 16:15

I\'ve got a ComboBox that contains paths to Images and I need to use the selected path as a source for an Image object. I\'ve tried to bind it like this:

...
<         


        
相关标签:
1条回答
  • 2021-01-27 16:32

    Since you are explicitly creating ComboBoxItems, you have to use their Content property to access the item object:

    Source="{Binding ElementName=ComboBox, Path=SelectedItem.Content}"
    

    Note that setting UpdateSourceTrigger=PropertyChanged has no effect in this Binding.


    Alternatively, you may set the ComboBox's SelectedValuePath property to "Content" and bind to SelectedValue instead of SelectedItem:

    <Image Source="{Binding ElementName=ComboBox, Path=SelectedValue}"/>
    ...
    <ComboBox Name="ComboBox" SelectedValuePath="Content">
        <ComboBoxItem IsSelected="True">Images/men.png</ComboBoxItem>
        <ComboBoxItem>Images/women.png</ComboBoxItem>
    </ComboBox>
    

    Another alternative would be to use String items instead of ComboBoxItems:

    xmlns:system="clr-namespace:System;assembly=mscorlib"
    ...
    <Image Source="{Binding ElementName=ComboBox, Path=SelectedItem}"/>
    ...
    <ComboBox Name="ComboBox" SelectedIndex="0">
        <system:String>Images/men.png</system:String>
        <system:String>Images/women.png</system:String>
    </ComboBox>
    
    0 讨论(0)
提交回复
热议问题