如何将枚举设置为 ItemsSource WPF

TMa*_*Man 4 wpf enums xaml

如何将枚举设置为 xaml 中的列表框。但是在列表框中,我需要显示描述而不是枚举的名称/值。然后当我单击一个按钮时,我需要通过 icommand 将选定的枚举作为枚举而不是字符串传递到方法中。例如:

  public enum MyEnum 
  {
     EnumOne = 0,
     [Description("Enum One")]
     EnumTwo = 1,
     [Description("Enum Two")]
     EnumTwo = 2,
     [Description("Enum Three")]
  }
Run Code Online (Sandbox Code Playgroud)

需要将这些枚举绑定到具有描述显示成员路径的列表框。然后根据列表框中的选择,传入所选的枚举,如下所示:

  private void ButtonDidClick(MyEnum enum)
  {

  }
Run Code Online (Sandbox Code Playgroud)

XAML:

  <ListBox ItemsSource="{Binding MyEnum"} /> ?
Run Code Online (Sandbox Code Playgroud)

而且我知道如何完成剩下的工作,只要将命令连接到按钮……等等。感谢您的帮助。

pap*_*zzo 5

来自生产应用程序
不久前得到了这个,找不到源
将 DisplayMememberPath 绑定到值

public static Dictionary<T, string> EnumToDictionary<T>()
    where T : struct
{
    Type enumType = typeof(T);

    // Can't use generic type constraints on value types,
    // so have to do check like this
    if (enumType.BaseType != typeof(Enum))
        throw new ArgumentException("T must be of type System.Enum");
    Dictionary<T, string> enumDL = new Dictionary<T, string>();
    foreach (T val in Enum.GetValues(enumType))
    {
        enumDL.Add(val, val.ToString());
    }
    return enumDL;
}
Run Code Online (Sandbox Code Playgroud)

获取描述方法

对于那些想知道如何读取描述属性值的人。以下可以轻松转换使用enum或扩展。我发现这个实现更加灵活。

使用此方法,替换val.ToString()GetDescription(val).

    /// <summary>
    /// Returns the value of the 'Description' attribute; otherwise, returns null.
    /// </summary>
    public static string GetDescription(object value)
    {
        string sResult = null;

        FieldInfo oFieldInfo = value.GetType().GetField(value.ToString());

        if (oFieldInfo != null)
        {
            object[] oCustomAttributes = oFieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), true);

            if ((oCustomAttributes != null) && (oCustomAttributes.Length > 0))
            {
                sResult = ((DescriptionAttribute)oCustomAttributes[0]).Description;
            }
        }
        return sResult;
    }
Run Code Online (Sandbox Code Playgroud)


dru*_*uss 5

使用 ObjectDataProvider:

<ObjectDataProvider x:Key="enumValues"
   MethodName="GetValues" ObjectType="{x:Type System:Enum}">
      <ObjectDataProvider.MethodParameters>
           <x:Type TypeName="local:ExampleEnum"/>
      </ObjectDataProvider.MethodParameters>
 </ObjectDataProvider>
Run Code Online (Sandbox Code Playgroud)

然后绑定到静态资源:

ItemsSource="{Binding Source={StaticResource enumValues}}"
Run Code Online (Sandbox Code Playgroud)

在这里找到了这个解决方案