开发者

Localization in a databound ComboBox isn't working correctly

I want to translate items of my combo box. So I use a personalized converter KeyToTranslationConverter which convert an Enum value to a translated string.

[ValueConversion(typeof(object), typeof(string))]
public class KeyToTranslationConverter : IValueConverter
{
    public object Convert(object value, Type targetType, 
                                  object parameter, CultureInfo culture)
    {
        return LocalizationResourcesManager.GetTranslatedText(value);
    }
}

My combo box is bound to the observable collection LanguagesEntries and the selectItem is bound to LanguageEntry attribute.

<ComboBox ItemsSource="{Binding LanguageEntries}" 
              SelectedItem="{Binding LanguageEntry}">
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <Label Content="{Binding Converter={StaticResource Converter}}"/>
        </DataTemplate>
    </ComboBox.ItemTemplate>
</Com开发者_高级运维boBox>

My problem is: When the user change the language the method is called :

CollectionViewSource.GetDefaultView(this.LanguageEntries).Refresh();

All items collections are translated except the selected item which is duplicated :

For example the selected item "Anglais" is not translated but the word English is in the combo box list.

Can someone help me.

Arnaud.


I had this exact problem, I solved it by binding the converter to the itemssource instead of the itemtemplate.

<ComboBox ItemsSource="{Binding LanguageEntries, Converter={StaticResource LanguageEntriesConverter}}">

And the convert need to handle the collection instead of each item:

    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if (value is System.Collections.ObjectModel.Collection<string>)
        {
            foreach (var c in (System.Collections.ObjectModel.Collection<string>)value)
            {
                c = LocalizationResourcesManager.GetTranslatedText(c);
            }
        }
        return value;
    }

The converter is called every time you update your itemssource either by assigning it to a new value or calling OnPropertyChanged.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜