WPF图像源与StringFormat绑定

问题描述:

我是WPF和MVVM(本周开始尝试使用它)并尝试在运行时绑定图像资源的新手。我想显示的项目包含一个枚举属性,指示项目的类型或状态:WPF图像源与StringFormat绑定

public class TraceEvent 
{ 
    /// <summary> 
    /// Gets or sets the type of the event. 
    /// </summary> 
    /// <value>The type of the event.</value> 
    public TraceEventType EventType { get; set; } 
} 

据我知道图片的来源属性有一个值转换器采用字符串并返回的Uri对象。

<Image Source="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}" /> 

那么,为什么上述工作没有?如果我直接进入uri(没有绑定),图像会完美显示。事实上,如果我做的一个TextBlock绑定和使用也显示没有问题,在图像中该值的结果:

<TextBlock Visibility="Collapsed" Name="bindingFix" Text="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}"/> 
<Image Source="{Binding ElementName=bindingFix, Path=Text}" /> 

我敢肯定,我在做什么可怕的错误的这样一个显而易见的事情处理图像。

谢谢。

我不确定这一个,但它似乎是传递图像的源属性一个字符串,它期望一个URI。所以,你必须将你的字符串转换成一个uri对象

只有当目标属性实际上是一个字符串时才使用StringFormat - Image.Source属性是一个Uri,所以绑定引擎不会应用StringFormat。

一种替代方法是使用Value Converter。可以编写一个在ConverterParameter中采用字符串格式的通用StringFormatConverter,或者一个更具体的ImageSourceConverter例如

public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
{ 
    return string.Format("/Images/{0}Icon.ico", value); 
} 

请注意,如果您的影像生活在,因为它们使用相同的组件,那么你不应该需要指定URI中的组件名称和上面的语法应该工作。