【问题标题】:WPF Binding - get path to Image from ComboBoxWPF Binding - 从 ComboBox 获取图像的路径
【发布时间】:2020-10-27 15:50:58
【问题描述】:

我有一个包含图像路径的组合框,我需要使用选定的路径作为图像对象的源。我试过这样绑定它:

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

我做错了什么?

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

    由于您明确创建 ComboBoxItems,您必须使用其 Content 属性来访问项目对象:

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

    请注意,设置 UpdateSourceTrigger=PropertyChanged 在此 Binding 中无效。


    或者,您可以将 ComboBox 的 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>
    

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-10
      • 1970-01-01
      • 2011-07-20
      相关资源
      最近更新 更多