我在这里有一个问题要问。我有一个在运行时在UI中显示的枚举。它有三个值。
enum ExpiryOptions
{
Never,
After,
On
}
现在从userControl加载其显示Never,After,on。
<ComboBox x:Name="accessCombo" Margin="5" Height="25" Width="80"
ItemsSource="{Binding Source={StaticResource ResourceKey=expiryEnum},
Converter={StaticResource enumtoLocalizeConverter}}"/>
在英语中很好,但问题是,如果软件用作本地化设置,则会显示相同的字符串。而不是任何本地化字符串。
在转换器中我写了一个像这样的代码
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
ExpiryOption[] myEnum = value; // This myEnum is having all the enum options.
// Now what shall I write here
//if I write a code like this
if(myEnum[0] == Properties.Resources.Never)
return Properties.Resources.Never;
else if(myEnum[1] == Properties.Resources.After)
return Properties.Resources.After;
else if(myEnum[2] == Properties.Resources.On)
return Properties.Resources.On;
}
然后UI中的枚举用英语语言设置中的N E V E R(垂直)填充。显然第一个字符串匹配并填充从不其他两个选项丢失。非常需要任何建议和帮助。
答案 0 :(得分:1)
您始终从转换器返回第一个枚举值,即字符串值Never
,这是char数组,因此您在组合框中看到一个项目作为单个字符。
相反,你应该返回字符串列表:
List<string> descriptions = new List<string>();
foreach(ExpiryOption option in myEnum)
{
if(option == Properties.Resources.Never)
descriptions.Add(Properties.Resources.Never);
else if(option == Properties.Resources.After)
descriptions.Add(Properties.Resources.After);
else if(option == Properties.Resources.On)
descriptions.Add(Properties.Resources.On);
}
return descriptions;
答案 1 :(得分:0)
您需要获取传递给ValueConverter的值,以便按如下方式使用它。
[ValueConversion(typeof(ExpiryOptions), typeof(string))]
public class MyEnumConverter: IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
ExpiryOptions option=
(ExpiryOptions)Enum.Parse(typeof(ExpiryOptions),value.ToString());
// Now that you have the value of the option you can use the culture info
// to change the value as you wish and return the changed value.
return option.ToString();
}
}
答案 2 :(得分:0)
假设您已将Never, After, On
的资源字符串分别定义为类Properties
中的字符串ExpiryOptionsNever, ExpiryOptionsAfter, ExpiryOptionsOn
(当然还有您需要的字符串),我会编写此转换器:
public class EnumConverter: IValueConverter{
public Dictionary<ExpiryOptions, string> localizedValues = new Dictionary<ExpiryOptions, string>();
public EnumConverter(){
foreach(ExpiryOptionsvalue in Enum.GetValues(typeof(ExpiryOptions)))
{
var localizedResources = typeof(Resources).GetProperties(BindingFlags.Static).Where(p=>p.Name.StartsWith("ExpiryOptions"));
string localizedString = localizedResources.Single(p=>p.Name="ExpiryOptions"+value).GetValue(null, null) as string;
localizedValues.Add(value, localizedString);
}
}
public void Convert(...){
return localizedValues[(ExpiryOptions)value];
}
}
这基本上是用户Blam在评论中建议的