当前位置:   article > 正文

MvvM中ComboBox绑定枚举值_mvvmlight 枚举 combox

mvvmlight 枚举 combox

定义枚举值:

  1. public enum Subjects
  2. {
  3. 语文,
  4. 数学,
  5. 英语,
  6. 体育
  7. }

方式一:

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

  1. <Window.Resources>
  2. <ObjectDataProvider x:Key="Subjects" MethodName="GetValues" ObjectType="{x:Type core:Enum}">
  3. <ObjectDataProvider.MethodParameters>
  4. <x:Type Type="viewModel:Subjects"/>
  5. </ObjectDataProvider.MethodParameters>
  6. </ObjectDataProvider>
  7. </Window.Resources>
  1. <ComboBox ItemsSource="{Binding Source={StaticResource Subjects}}" SelectedItem="{Binding Subject1}"/>
  2. <Label Grid.Column="1" Content="{Binding Sub1}"/>

ViewModel代码:

  1. private Subjects _subject1;
  2. public Subjects Subject1
  3. {
  4. get { return _subject1; }
  5. set
  6. {
  7. _subject1 = value;
  8. Sub1 = value.ToString();
  9. this.RaisePropertyChanged("Subject1");
  10. }
  11. }
  12. private string _sub1 = "初始值";
  13. public string Sub1
  14. {
  15. get { return _sub1; }
  16. set
  17. {
  18. _sub1 = value;
  19. this.RaisePropertyChanged("Sub1");
  20. }
  21. }

方式二:

xaml文件:是SelectedValue而不是SelectedItem

  1. <ComboBox ItemsSource="{Binding Subs}" DisplayMemberPath="Value" SelectedValuePath="Key" SelectedValue="{Binding Subject1}"/>
  2. <Label Grid.Column="1" Content="{Binding Sub1}"/>

ViewModel代码:

  1. private Dictionary<Subjects, string> _subs;
  2. public Dictionary<Subjects, string> Subs
  3. {
  4. get { return _subs; }
  5. set
  6. {
  7. _subs = value;
  8. this.RaisePropertyChanged("Subs");
  9. }
  10. }
  11. public MainWindowViewModel()
  12. {
  13. Subs = new Dictionary<Subjects, string>();
  14. foreach (Subjects em in Enum.GetValues(typeof(Subjects)))
  15. Subs[em] = "学科:" + em.ToString();
  16. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/人工智能uu/article/detail/928563
推荐阅读
相关标签
  

闽ICP备14008679号