WPF绑定-从组合框获取图像的路径



我有一个包含Images路径的ComboBox,我需要使用所选路径作为Image对象的源。我试过这样绑定它:

...
<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>
...

我做错了什么?

由于显式创建ComboBoxItems,因此必须使用其Content属性来访问项对象:

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

请注意,设置UpdateSourceTrigger=PropertyChanged在此绑定中没有任何作用。


或者,您可以将组合框的SelectedValuePath属性设置为"Content",并绑定到SelectedValue而不是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>

另一种选择是使用字符串项而不是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>

最新更新