我有一个枚举
public enum AccountType
{
Cash,
PrepaidCard,
CreditCard,
Project
}
这是 ItemsSource 的代码
typeComboxBox.ItemsSource = Enum.GetValues(typeof(AccountType)).Cast<AccountType>();
我想用多语言转换器将它绑定(bind)到我的组合框
我怎样才能做到这一点?
最佳答案
我在本地化方面没有做太多工作,但我可能会使用自定义转换器来解决这个问题。 (当您使用 ComboBox
时,我假设您正在开发 Windows Phone Store 应用程序,而不是 Windows Phone Silverlight 应用程序)。
1:将枚举值的翻译添加到不同的 Resources.resw
文件(例如,美国英语的 /Strings/en-US/Resources.resw
,请参阅 http://code.msdn.microsoft.com/windowsapps/Application-resources-and-cd0c6eaa ),该表将类似于:
|-------------|--------------|--------------|
| Name | Value | Comment |
|-------------|--------------|--------------|
| Cash | Cash | |
| PrepaidCard | Prepaid card | |
| CreditCard | Credit card | |
| Project | Project | |
2:然后创建一个自定义转换器:
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:将其添加到 App.xaml
中的资源字典中,例如:
<Application.Resources>
<local:LocalizationConverter x:Key="LocalizationConverter" />
</Application.Resources>
4:在ComboBox
中,创建一个使用此转换器的项目模板:
<ComboBox x:Name="typeComboxBox">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Converter={StaticResource LocalizationConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
可能有一种更简单的方法,但这是我现在能想到的最好的方法。
关于c# - XAML 中的枚举转换器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23952052/