我是 WPF 和 MVVM 的新手(本周开始尝试)并尝试在运行时绑定(bind)图像资源。我尝试显示的项目包含指示项目类型或状态的枚举属性:
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(没有绑定(bind)),图像会完美显示。事实上,如果我在 TextBlock 中进行绑定(bind)并在图像中使用该值的结果也毫无问题地显示:
<TextBlock Visibility="Collapsed" Name="bindingFix" Text="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}"/>
<Image Source="{Binding ElementName=bindingFix, Path=Text}" />
我敢肯定,对于如此明显的图像处理,我犯了严重的错误。
谢谢。
最佳答案
仅当目标属性实际上是一个字符串时才使用 StringFormat - Image.Source 属性是一个 Uri,因此绑定(bind)引擎不会应用 StringFormat。
一种替代方法是使用 Value Converter .要么写一个通用的 StringFormatConverter,在 ConverterParameter 中采用字符串格式,要么写一个更具体的 ImageSourceConverter,例如
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format( "/Images/{0}Icon.ico", value );
}
请注意,如果您的图像与其使用时位于同一个程序集中,则您不需要在 URI 中指定程序集名称并且上述语法应该有效。
关于WPF 图像源与 StringFormat 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3429851/