uncletall uncletall - 1 year ago 151
C# Question

WPF use binding to assign static resource

I am trying to use an enum to display a corresponding image. For this I have a value converter that converts an enum to the correct resource name. My resources are defined as follows:

<BitmapImage x:Key="AlarmCat1" UriSource="/Lib.Infrastructure;component/Resources/msg_cat1.bmp" />
<BitmapImage x:Key="AlarmCat2" UriSource="/Lib.Infrastructure;component/Resources/msg_cat2.bmp" />
<BitmapImage x:Key="AlarmCat3" UriSource="/Lib.Infrastructure;component/Resources/msg_cat3.bmp" />
<converters:JamCategoryToImageConverter x:Key="AlarmCategoryConverter" />

This works:

<Image Source="{StaticResource AlarmCat1}" />

But this doesn't, the converter is called and the correct value is passed back. What is the correct syntax?

<Image Source="{StaticResource { Binding CurrentAlarmItem.AlarmCategory, Converter={StaticResource AlarmCategoryConverter}}}" />

For completeness, this is the convert function:

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
switch ((AlarmCategory)value)
case AlarmCategory.Category1:
return "AlarmCat1";
case AlarmCategory.Category2:
return "AlarmCat2";
case AlarmCategory.Category3:
return "AlarmCat3";
return null;

Answer Source

I would return the resource in the converter:

<Image Source="{Binding CurrentAlarmItem.AlarmCategory, Converter={StaticResource AlarmCategoryConverter}}" />

In your converter do something like this:

return Application.Current.FindResource("AlarmCat1") as BitmapImage;

Set your resources for the complete application with the use of resourcedictionary (app.xaml)

            <ResourceDictionary Source="Dictionary1.xaml" />

In your Dictionary (Dictionary1.xaml)

<BitmapImage x:Key="AlarmCat1" UriSource="bh.jpg" />

Because your resources are now defined on applicationlevel, the code will now find your resource and give it back.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download