分享

C# WPF mvvm模式下combobox绑定(list<enum>、Dictionary<int,string>)

 ontheroad96j47 2021-11-08

ComboBox是一个非常常用的界面控件,它的数据源ItemsSource既可以绑定一个List列表,也可以是一个字典,本篇文章就讲这些内容展开讲解。

01

前言

      ComboBox一个非常常用的下拉菜单界面控件的数据源ItemsSource既可以绑定一个List列表,也可以是一个字典本篇文章就讲这些内容展开讲解

      首先,讲解几个常用的属性概念:

ItensSource:用于指定下拉列表绑定的List<string>数据对象;

SelectedIndex :下拉列表中选中行的索引;

DisplayMemberPath:下拉列表中要显示的List<T>数据对象的列,因为List<T>数据对象可能会有多列;

SelectedValuePath:下拉列表中,对应与显示的List<T>数据对象的列,返回的List<T>数据对象的列;

02


绑定ObservableCollection<T>

① 第一种情况T为一个普通学生类时:

类的定义:

public class Students { public int ID { get; set; } public string Name { get; set; } }

数据绑定:

<dxlc:LayoutItem Margin="10,0,0,0" FontSize="13" Label="StudentName" HorizontalContentAlignment="Right"> <ComboBox Width="150" HorizontalAlignment="Left" SelectedIndex="2" DisplayMemberPath="Name" ItemsSource="{Binding StudentList, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> </dxlc:LayoutItem>

viewmodel中:

public ObservableCollection<Students> StudentList { get; set; } = new ObservableCollection<Students>();
StudentList.Add(new Students() { ID = 1, Name = "xiao zhu"}); StudentList.Add(new Students() { ID = 2, Name = "xiao Li" }); StudentList.Add(new Students() { ID = 3, Name = "xiao Wang" }); StudentList.Add(new Students() { ID = 4, Name = "xiao Zhang" });

第二种情况T为HumanSkinColors的枚举类型时:

枚举定义:

public enum HumanSkinColors{ Yellow, White, Black }

数据绑定:

<dxlc:LayoutItem Margin="10,0,0,0" FontSize="13" Label="HumanSkinColor" HorizontalContentAlignment="Right"> <dxe:ComboBoxEdit Width="150" HorizontalAlignment="Left" SelectedIndex="0" ItemsSource="{Binding HumanSkinList, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> </dxlc:LayoutItem>

viewmodel代码:

public ObservableCollection<Students> StudentList { get; set; } = new ObservableCollection<Students>();
foreach (HumanSkinColors HumanSkinColor in Enum.GetValues(typeof(HumanSkinColors))) { HumanSkinList.Add(HumanSkinColor); }

03


绑定Dictionary<T,T>

字典的定义:

public Dictionary<int,string> StudentDic { get; set; } = new Dictionary<int, string>();

数据绑定:

<dxlc:LayoutItem Margin="10,0,0,0" FontSize="13" Label="StudentName" HorizontalContentAlignment="Right"> <ComboBox Width="150" HorizontalAlignment="Left" SelectedIndex="3" DisplayMemberPath="Value" SelectedValuePath="Key" ItemsSource="{Binding StudentDic}" /> </dxlc:LayoutItem>

viewmodel代码:

StudentDic.Add(1, "xiao zhu"); StudentDic.Add(2, "xiao Li"); StudentDic.Add(3, "xiao Wang"); StudentDic.Add(4, "xiao Zhang");

04


结果展示

05


源码下载

链接:https://pan.baidu.com/s/1azXzP8Xtp8488pN0s1C4Uw

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约