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:
...
<Border BorderBrush="Black" BorderThickness="1" Grid.Row="0" Grid.Column="2" Grid.RowSpan="3" Width="50" Height="50" Margin="10, 10, 10, 6" VerticalAlignment="Bottom">
<Image Name="Image" Source="{Binding ElementName=ComboBox, Path=SelectedItem.Value, UpdateSourceTrigger=PropertyChanged}"/>
</Border>
...
<ComboBox Name="ComboBox" Grid.Row="2" Grid.Column="1" Margin="4" VerticalAlignment="Center">
<ComboBoxItem IsSelected="True">Images/men.png</ComboBoxItem>
<ComboBoxItem>Images/women.png</ComboBoxItem>
</ComboBox>
...
What am I doing wrong?
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.