Bolt Delta
Bolt Delta

Reputation: 215

Enum converter in XAML

I have an enum

public enum AccountType
{
    Cash,
    PrepaidCard,
    CreditCard,
    Project
}

And this is code for ItemsSource

typeComboxBox.ItemsSource = Enum.GetValues(typeof(AccountType)).Cast<AccountType>();

And I want binding it to my ComboBox like this with multilanguage converter

Maybe multilanguages converter

enter image description here

How can I do that?

Upvotes: 2

Views: 3154

Answers (1)

Johan Falk
Johan Falk

Reputation: 4359

I haven't worked a lot with localization, but I would probably solve this using a custom converter. (As you use a ComboBox I assume you are doing a Windows Phone Store app, and not a Windows Phone Silverlight app).

1: Add translations for the enum values to the different Resources.resw files (e.g. /Strings/en-US/Resources.resw for US English, see http://code.msdn.microsoft.com/windowsapps/Application-resources-and-cd0c6eaa), the table will look something like:

|-------------|--------------|--------------|
| Name        | Value        | Comment      |
|-------------|--------------|--------------|
| Cash        | Cash         |              |
| PrepaidCard | Prepaid card |              |
| CreditCard  | Credit card  |              |
| Project     | Project      |              |

2: Then create a custom converter:

public class LocalizationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        return ResourceLoader.GetForCurrentView().GetString(value.ToString());
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new NotImplementedException();
    }
}

3: Add this to the resource Dictionary in App.xaml for example:

<Application.Resources>
    <local:LocalizationConverter x:Key="LocalizationConverter" />
</Application.Resources>

4: In the ComboBox, create an item template which uses this converter:

<ComboBox x:Name="typeComboxBox">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Converter={StaticResource LocalizationConverter}}" />
        </DataTemplate>
    </ComboBox.ItemTemplate>
</ComboBox>

There might be an easier way, but this is the best one I can Think of right now.

Upvotes: 5

Related Questions