WPF绑定-从ComboBox获取图像的路径 [英] WPF Binding - get path to Image from ComboBox

查看:64
本文介绍了WPF绑定-从ComboBox获取图像的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ComboBox,其中包含指向Images的路径,我需要将所选路径用作Image对象的源.我试图这样绑定它:

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

我在做什么错了?

推荐答案

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

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}"

请注意,设置 UpdateSourceTrigger = PropertyChanged 在此绑定中无效.

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

或者,您可以将ComboBox的 SelectedValuePath 属性设置为"Content" 并绑定到 SelectedValue 而不是 SelectedItem :

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>


另一种替代方法是使用字符串项而不是ComboBoxItems:


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>

这篇关于WPF绑定-从ComboBox获取图像的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆