Search code examples
c#wpfxamllocalizationresx

Bind string from .resx ResourceDictionary to TextBlock.Text using index key


i'm trying to get my view in different languages, using Properties/Resources.resx file for localization.

I've my model looks like the following:

class City 
{
    public int Id { get; set; }
    public string LocalizationKey { get; set; }
}

The ViewModel:

class ViewModel
{
    public ObservableCollection<City> Cities { get; set; }
}

And on my View, i've the following code:

<ItemsControl ItemsSource="{Binding Cities}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding LocalizationKey}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

When i want to get the value of my string key from the dictionary for only one item without Items Collection it works correctly by using the following code:

<TextBlock Text="{x:Static properties:Resources.MyStringKey}" />

The problem is when using the code above with an ItemsControl where the keys are unknowns! Is there any way to access to the dictionary values by using the LocalizationKey as an index?


Solution

  • After hours of web searching, i finally found a solution by using a converter, it may not the best practices to solve the problem but at least it does exactly what i want:

    My Converter:

    public class LocalizationConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var key = value as string;
            if (!string.IsNullOrEmpty(key))
            {
                string dictionaryValue = Resources.ResourceManager.GetString(key);
                return dictionaryValue ?? key;
            }
            return value;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
    

    and the XAML code:

    <TextBlock Text="{Binding LocalizationId, Converter={StaticResource LocalizationConverter}}" />
    

    Thanks.