问题描述
我新的WPF和MVVM,并试图图片资源在运行时绑定(本周用它进行试验启动)。我想显示的项目包含一个枚举属性,指示项目的类型或状态:
I'm new to WPF and MVVM (started this week experimenting with it) and trying to bind image resources at runtime. The items I'm trying to display contain an enumerate property that indicates the type or state of the item:
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对象。
As far as I known the Source attribute of Image has a value converter that takes strings and returns Uri objects.
<Image Source="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}" />
那么,为什么不上面的工作?如果我直接输入URI(不绑定)图像显示完美。事实上,如果我做一个TextBlock的绑定和使用也显示没有问题在图像该值的结果是:
So why doesn't the above work? If I enter the uri directly (without binding) the image is shown perfectly. In fact, if I do the binding in a TextBlock and use the result of that value in the Image also shown without problem:
<TextBlock Visibility="Collapsed" Name="bindingFix" Text="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}"/>
<Image Source="{Binding ElementName=bindingFix, Path=Text}" />
我是pretty知道我在做什么可怕的错误的这样一个明显的事情与图像。
I'm pretty sure I'm doing something terrible wrong for such an obvious thing to do with images.
感谢。
推荐答案
如果目标属性实际上是一个字符串的StringFormat仅用于 - 在Image.Source属性是一个开放的,以便绑定引擎将不适用的StringFormat
StringFormat is only used if the target property is actually a string - the Image.Source property is a Uri so the binding engine won't apply the StringFormat.
一替代方法是使用一个值转换一>。无论是写通用StringFormatConverter,是以字符串格式在ConverterParameter,或者更具体的ImageSourceConverter例如
One alternative is to use a Value Converter. Either write a general StringFormatConverter that takes the string format in the ConverterParameter, or a more specific ImageSourceConverter e.g.
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format( "/Images/{0}Icon.ico", value );
}
请注意,如果您的图像居住在,因为它们使用相同的组件,那么你不应该需要在URI指定的程序集名称和上面的语法应该工作。
Note that if your images live in the same assembly as they are used, then you shouldn't need to specify the assembly name in the URI and the above syntax should work.
这篇关于WPF图像源与绑定的StringFormat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!