【问题标题】:How do I bind an enum to my listbox?如何将枚举绑定到我的列表框?
【发布时间】:2011-04-25 13:22:48
【问题描述】:

我有一个 Silverlight (WP7) 项目,想将一个枚举绑定到一个列表框。这是一个具有自定义值的枚举,位于类库中。我该怎么做?

【问题讨论】:

标签: c# xaml windows-phone-7


【解决方案1】:

【讨论】:

    【解决方案2】:

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

    静态方法将返回可枚举的字符串集合。您可以将其绑定到列表框的项目源。喜欢

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

    【讨论】:

    • 那么,下一个问题是,如何通过绑定将选定的枚举值分配回视图模型中的属性?我一直在寻找答案,但找不到任何资源,感谢任何方向。谢谢。
    • @K2so 您可以将视图模型中的属性绑定到ListBoxSelectedItem 属性。检查以下可以帮助您的示例。 sites.google.com/site/html5tutorials/BindingEnum.zip
    • 介意我在我的PhoneyTools项目中借用这个代码和属性给你,以便人们可以使用它吗? phoney.codeplex.com?
    • @Shawn Wildermuth 我很荣幸 :) 我是你博客的忠实粉丝 :)
    • [描述]属性呢?当枚举需要更好的字符串表示时,使用它通常很有帮助。你不在这里处理那个案子。
    【解决方案3】:

    将枚举转换为列表(或类似列表) - 根据 How do I convert an enum to a list in C#?

    然后绑定到转换后的列表。

    【讨论】:

      猜你喜欢
      • 2011-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-21
      • 1970-01-01
      • 2012-05-05
      • 2013-03-24
      • 2010-09-28
      相关资源
      最近更新 更多