使用StringFormat绑定WPF图像源

nul*_*ull 3 wpf binding image string-formatting mvvm

我是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; }
}
Run Code Online (Sandbox Code Playgroud)

据我所知,Image的Source属性有一个值转换器,它接受字符串并返回Uri对象.

<Image Source="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}" />
Run Code Online (Sandbox Code Playgroud)

那么为什么上面的工作没有呢?如果我直接输入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}" />  
Run Code Online (Sandbox Code Playgroud)

我非常肯定我正在做一些与图像这么明显的事情有关的错误.

谢谢.

Phi*_*ney 6

StringFormat仅在目标属性实际上是字符串时使用 - Image.Source属性是Uri,因此绑定引擎不会应用StringFormat.

一种替代方法是使用值转换器.编写一个采用ConverterParameter中的字符串格式的通用StringFormatConverter,或者更具体的ImageSourceConverter,例如:

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

请注意,如果您的图像与使用的图像位于同一个程序集中,则您不需要在URI中指定程序集名称,并且上述语法应该有效.