Echarnus
Echarnus

Reputation: 87

Converting a static property to a StaticResource in WPF

I was wondering whether it was possible to convert a static property of a class into a static resource.

The reason I want to do this is because I made a converter which translates values of an enum into a human friendly readable format (translates them into another language).

Because I didn't want to make a converter per enum, I wanted to make things more generic and use one converter with two properties, the type of the enum and the dictionary (IDictionary<string, string>) to map the enum to the wanted output.

public class EnumTranslatorConverter : IValueConverter
{

    public Type EnumType { get; set; }
    public IDictionary<string, string> EnumMapping { get; set; }

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return EnumMapping[value.ToString()];
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return Enum.Parse(EnumType, value as string);
    }
}

Then I got a resource where I define my Converters, for a more convenient use of them inside my application.

I wanted to define a converter for each type and mapping, this is merely a proof of concept as it's of course not working:

<mappings:DisplayMappings x:Key="displaymappings" />
<my:EnumTranslatorConverter x:Key="DayOfWeekTranslatorConverter" 
    EnumType="{x:Type sys:DayOfWeek}" 
    EnumMapping="{Binding Source={StaticResource displaymappings}, Path=DayOfWeekMapping}" />

The EnumType property is working. But the EnumMapping of course isn't as it requires a static resource as it's not a dependency property.

But how can I inject my mapping into the property using XAML? Is there some way to create a static resource out of a static property in XAML?

Upvotes: 1

Views: 765

Answers (2)

russw_uk
russw_uk

Reputation: 1267

What might be a more straightforward approach is to do away with the separate mapping and make use of a [Description("...")] attribute [(see [MSDN])] attached to the members of your enumeration.

In your converter you can then construct the map dynamically and cache it per type by reflecting over the enumeration's members and instantiating the type.

That has the advantage that you do not need to maintain a separate dictionary to map the enumeration members names in the Xaml, which could potentially become out of sync with your enum members at some point in the future.

Upvotes: 0

ASh
ASh

Reputation: 35722

there is a markup extension for static properties: {x:Static}

<my:EnumTranslatorConverter x:Key="DayOfWeekTranslatorConverter" 
     EnumType="{x:Type sys:DayOfWeek}" 
     EnumMapping="{x:Static mappings:DisplayMappings.DayOfWeekMapping}" />

Upvotes: 1

Related Questions