Databinding an enum property to a ComboBox in WPF

后端 未结 13 1382
北海茫月
北海茫月 2020-11-22 15:46

As an example take the following code:

public enum ExampleEnum { FooBar, BarFoo }

public class ExampleClass : INotifyPropertyChanged
{
    private ExampleEn         


        
13条回答
  •  花落未央
    2020-11-22 16:14

    Here is a generic solution using a helper method. This can also handle an enum of any underlying type (byte, sbyte, uint, long, etc.)

    Helper Method:

    static IEnumerable GetEnum() {
        var type    = typeof(T);
        var names   = Enum.GetNames(type);
        var values  = Enum.GetValues(type);
        var pairs   =
            Enumerable.Range(0, names.Length)
            .Select(i => new {
                    Name    = names.GetValue(i)
                ,   Value   = values.GetValue(i) })
            .OrderBy(pair => pair.Name);
        return pairs;
    }//method
    
    
    

    View Model:

    public IEnumerable EnumSearchTypes {
        get {
            return GetEnum();
        }
    }//property
    
    
    

    ComboBox:

    
    

    提交回复
    热议问题