2010-10-14 77 views
5

我有一個Silverlight(WP7)項目,並希望將一個枚舉綁定到一個列表框。這是一個帶有自定義值的枚舉,坐在類庫中。我該怎麼做呢?如何將枚舉綁定到我的列表框?

+1

可能的重複[數據綁定枚舉屬性到WPF中的ComboBox](http://stackoverflow.com/questions/58743/databinding-an-enum-property-to-a-combobox-in-wpf) – Andrey 2010-10-14 17:46:36

回答

11

在Silverlight(WP7)中,Enum.GetNames()方法不可用。您可以使用以下內容

public class Enum<T> 
{ 
    public static IEnumerable<string> GetNames() 
    { 
     var type = typeof(T); 
     if (!type.IsEnum) 
      throw new ArgumentException("Type '" + type.Name + "' is not an enum"); 

     return (
      from field in type.GetFields(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static) 
      where field.IsLiteral 
      select field.Name).ToList<string>(); 
    } 
} 

靜態方法將返回可枚舉的字符串集合。你可以將它綁定到一個列表框的itemssource。像

this.listBox1.ItemSource = Enum<Colors>.GetNames(); 
+0

然後,接下來的問題是,如何將具有綁定的選定枚舉值分配回視圖模型中的屬性?我一直在尋找答案,但找不到任何資源,任何方向指出讚賞。謝謝。 – K2so 2010-11-22 04:54:24

+1

@ K2so您可以將視圖模型中的屬性綁定到ListBox的SelectedItem屬性。檢查以下樣本可以幫助你。 https://sites.google.com/site/html5tutorials/BindingEnum.zip – 2010-11-22 05:27:15

+0

請注意,如果我在我的PhoneyTools項目中借用了此代碼和屬性,以便人們可以使用它? http://phoney.codeplex.com? – 2011-03-24 07:15:36