指定图像的来源

时间:2012-01-04 15:26:38

标签: c# wpf image

我有以下非常简单的代码,当然有效:

<Image Source="Resources\data_store.png"/>

问题是我现在必须从作为ItemSource给出的对象的属性(“name”)中获取字符串,并且我没有设法绑定它

我尝试了这些但没有工作:

<Image Source=name/>
<Image Source=Path="name"/>
<Image Source=Path=name/>
<Image Source={Path="name"}/>
<Image Source={Path=name}/>
<Image Source={Binding name}/>

我的对象是在c#codebehind中设置的,我认为它不会改变某些东西......

2 个答案:

答案 0 :(得分:2)

在后面的代码中,确保将源定义为Property:

public string Name{get;set;}

然后绑定的工作原理如下:

<Image Source="{Binding Name, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type UserControl}}}" />

如果要动态更新图像,则需要实现INotifyPropertyChanged并在图像更改时调用PropertyChanged

答案 1 :(得分:1)

当遇到XAML解析器时,它非常聪明:

<Image Source="Resources\data_store.png"/>

它知道Source属性是ImageSource并且将使用合适的转换器来加载指定的资源。如果您需要在代码隐藏或通过绑定设置图像源,您需要通过值转换器自己完成。以下值转换器将起到作用:

public classImageUriConverter : IValueConverter
{
    publicImageUriConverter()
    {
    }

    public objectConvert(objectvalue, TypetargetType, objectparameter, System.Globalization.CultureInfo culture)
    {
       Urisource = (Uri)value;
        return newBitmapImage(source);
    }

    public objectConvertBack(objectvalue, TypetargetType, objectparameter, System.Globalization.CultureInfo culture)
    {
        throw newNotImplementedException();
    }

 }

this blog post提供。

相关问题