Databinding an enum property to a ComboBox in WPF

后端 未结 13 1498
北海茫月
北海茫月 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:26

    I prefer not to use the name of enum in UI. I prefer use different value for user (DisplayMemberPath) and different for value (enum in this case) (SelectedValuePath). Those two values can be packed to KeyValuePair and stored in dictionary.

    XAML

     
    

    C#

    public Dictionary ExampleEnumsWithCaptions { get; } =
        new Dictionary()
        {
            {ExampleEnum.FooBar, "Foo Bar"},
            {ExampleEnum.BarFoo, "Reversed Foo Bar"},
            //{ExampleEnum.None, "Hidden in UI"},
        };
    
    
    private ExampleEnum example;
    public ExampleEnum ExampleProperty
    {
        get { return example; }
        set { /* set and notify */; }
    }
    

    EDIT: Compatible with the MVVM pattern.

提交回复
热议问题