MvvM中ComboBox绑定枚举值

定义枚举值:

public enum Subjects
{
    语文,
    数学,
    英语,
    体育
}

方式一:

xaml文件:需要引入xmlns:core="clr-namespace:System;assembly=mscorlib";其中枚举我是写在ViewModel中的,所以还需要引入xmlns:viewModel="clr-namespace:WriteTXT.ViewModels"

MvvM中ComboBox绑定枚举值_第1张图片


    
        
            
        
    

ViewModel代码:

private Subjects _subject1;

public Subjects Subject1
{
    get { return _subject1; }
    set
    {
        _subject1 = value;
        Sub1 = value.ToString();
        this.RaisePropertyChanged("Subject1");
    }
}

private string _sub1 = "初始值";

public string Sub1
{
    get { return _sub1; }
    set
    {
        _sub1 = value;
        this.RaisePropertyChanged("Sub1");
    }
}

方式二:

xaml文件:是SelectedValue而不是SelectedItem


ViewModel代码:

private Dictionary _subs;

public Dictionary Subs
{
    get { return _subs; }
    set
    {
        _subs = value;
        this.RaisePropertyChanged("Subs");
    }
}

public MainWindowViewModel()
{
    Subs = new Dictionary();
    foreach (Subjects em in Enum.GetValues(typeof(Subjects)))
        Subs[em] = "学科:" + em.ToString();
}

 

你可能感兴趣的:(C#)