我是WPF和MVVM的新手(本周开始尝试它)并尝试在运行时绑定图像资源 . 我正在尝试显示的项目包含一个枚举属性,指示项目的类型或状态:
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; }
}
据我所知,Image的Source属性有一个值转换器,它接受字符串并返回Uri对象 .
<Image Source="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}" />
那么为什么上面的工作没有呢?如果我直接输入uri(没有绑定),图像就会完美显示 . 实际上,如果我在TextBlock中进行绑定并在Image中使用该值的结果也没有问题:
<TextBlock Visibility="Collapsed" Name="bindingFix" Text="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}"/>
<Image Source="{Binding ElementName=bindingFix, Path=Text}" />
我非常肯定我正在做一些与图像这么明显的事情有关的错误 .
谢谢 .
2 回答
StringFormat仅在目标属性实际上是字符串时使用 - Image.Source属性是Uri,因此绑定引擎不会应用StringFormat .
一种替代方法是使用Value Converter . 编写一个采用ConverterParameter中的字符串格式的通用StringFormatConverter,或者更具体的ImageSourceConverter,例如:
请注意,如果您的图像与使用的图像位于同一个程序集中,则您不需要在URI中指定程序集名称,并且上述语法应该有效 .
我不确定这个,但似乎你传递图像的源属性一个字符串,它期望一个uri . 所以,你必须将你的字符串转换为uri对象