开发者

WPF Image Source binding with StringFormat

I'm new to WPF and MVVM (started this week experimenting with it) and trying to bind image resources at runtime. The items I'm trying to display contain an enumerate property that indicates the type or state of the item:

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; }
}

As far as I known the Source attribute of Image has a value converter that takes strings and returns Uri objects.

<Image Source="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}" />

So why doesn't the above work? If I enter the uri directly (without binding) the image is shown perfectly. In fact, if I do the binding in a TextBlock and use the result o开发者_如何学Gof that value in the Image also shown without problem:

<TextBlock Visibility="Collapsed" Name="bindingFix" Text="{Binding Path=EventType, StringFormat={}/AssemblyName;component/Images/{0}Icon.ico}"/>
<Image Source="{Binding ElementName=bindingFix, Path=Text}" />  

I'm pretty sure I'm doing something terrible wrong for such an obvious thing to do with images.

Thanks.


StringFormat is only used if the target property is actually a string - the Image.Source property is a Uri so the binding engine won't apply the StringFormat.

One alternative is to use a Value Converter. Either write a general StringFormatConverter that takes the string format in the ConverterParameter, or a more specific ImageSourceConverter e.g.

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

Note that if your images live in the same assembly as they are used, then you shouldn't need to specify the assembly name in the URI and the above syntax should work.


i'm not sure about this one but it seems that you are passing the image's source property a string where it expects a uri. so, you have to convert your string into a uri object

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜