2014-01-29 49 views
2

我在这里有一个问题要问。我有一个运行时在UI中显示的枚举。它有三个值。如何将枚举转换为WPF中的本地化枚举结构

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ëR(垂直地)在英语语言设置填充。显然,第一个字符串匹配并填充从不其他两个选项都没有丢失。任何建议和帮助是非常必要的。

+0

我的东西,在一本字典的枚举建议。键是枚举,值是我想要显示的字符串。 – Paparazzi

回答

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();   
    } 
} 
1

你总是从转换器即字符串值Never这是字符数组,因此你看到一个项目在你的组合框单个字符返回第一个枚举值。在Properties类作为ExpiryOptionsNever, ExpiryOptionsAfter, ExpiryOptionsOn(你需要字符串,当然)

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; 
0

假设你已经定义的资源字符串Never, After, On作为字符串分别我会写这个转换器:

相反,你应该返回字符串列表

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]; 
    } 
} 

实际上,这就是用户布拉姆在评论