我是 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 中进行绑定并在图像中使用该值的结果,也不会出现问题:
<TextBlock Visibility="Collapsed" Name="bindingFix" Text="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}"/>
<Image Source="{Binding ElementName=bindingFix, Path=Text}" />
我很确定我在与图像有关的如此明显的事情上做了一些可怕的错误。
Thanks.
仅当目标属性实际上是字符串时才使用 StringFormat - Image.Source 属性是 Uri,因此绑定引擎不会应用 StringFormat。
一种替代方法是使用值转换器 http://msdn.microsoft.com/en-us/library/system.windows.data.ivalueconverter.aspx。要么编写一个在 ConverterParameter 中采用字符串格式的通用 StringFormatConverter,要么编写一个更具体的 ImageSourceConverter,例如
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return string.Format( "/Images/{0}Icon.ico", value );
}
请注意,如果您的图像与使用的程序集位于同一个程序集中,则您不需要在 URI 中指定程序集名称,并且上述语法应该可以工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)