本地化语言标记以显示名称转换器

时间:2014-02-21 15:28:36

标签: c# wpf binding localization converter

我想转换本地化元标记,例如en-US显示名称,在本例中为英文。元标记存储在ObservableCollection中,因为它将在运行时修改。我想将显示名称绑定到组合框。

组合框:

<ComboBox Grid.Column="1" Grid.Row="1" Width="200" VerticalAlignment="Center" HorizontalAlignment="Center" SelectedIndex="0" ItemsSource="{Binding Path=ServerData.AvailableTemplateLanguages}">
       <ComboBox.ItemTemplate>
            <DataTemplate>
                   <TextBlock Text="{Binding, Converter=LanguageTagToNameConverter}" FontSize="12"/>
            </DataTemplate>
       </ComboBox.ItemTemplate>
</ComboBox>

转换器:

 class LanguageTagToNameConverter : IValueConverter
{
    public object Convert(object value,
                          Type targetType,
                          object parameter,
                          CultureInfo culture)
    {
        return CultureInfo.GetCultureInfo(value.ToString()).DisplayName;
    }


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

的ObservableCollection:

 public class ServerDataObj : ModelBase
{
    private ObservableCollection<string> _availableTemplateLanguages = new ObservableCollection<string> { "de-DE", "en-US" };
    public ObservableCollection<string> AvailableTemplateLanguages 
    { 
        get 
        {
            return _availableTemplateLanguages; 
        }
        set 
        {
            _availableTemplateLanguages = value;
            OnPropertyChanged("AvailableTemplateLanguages");
        }
    }
}

不幸的是,这种方法不起作用。

1 个答案:

答案 0 :(得分:1)

您需要将转换器放入资源:

<Window>
    <Window.Resources>
        <LanguageTagToNameConverter x:Key="convLang"/>
    </Window.Resources>

    ...

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