2014-01-29 44 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]; 
    } 
} 

實際上,這就是用戶布拉姆在評論