2010-10-14 72 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