【问题标题】:WPF Image Source binding with StringFormatWPF 图像源与 StringFormat 绑定
【发布时间】:2011-03-26 16:24:08
【问题描述】:

我是 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}" />  

我很确定我做错了什么,因为与图像有关的如此明显的事情。

谢谢。

【问题讨论】:

    标签: wpf image mvvm binding string-formatting


    【解决方案1】:

    StringFormat 仅在目标属性实际上是字符串时使用 - Image.Source 属性是 Uri,因此绑定引擎不会应用 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 中指定程序集名称,上述语法应该可以工作。

    【讨论】:

      【解决方案2】:

      我不确定这个,但似乎您正在向图像的源属性传递一个字符串,它需要一个 uri。所以,你必须将你的字符串转换成一个 uri 对象

      【讨论】:

        猜你喜欢
        • 2011-08-17
        • 2010-10-19
        • 1970-01-01
        • 2011-03-11
        • 2013-01-11
        • 2017-10-09
        • 1970-01-01
        • 2010-12-29
        • 2017-02-16
        相关资源
        最近更新 更多