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

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

01

前言

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

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

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

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

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

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

02

绑定ObservableCollection

① 第一种情况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”>

</dxlc:LayoutItem>
viewmodel中:

public ObservableCollection StudentList { get; set; } = new ObservableCollection();
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 StudentList { get; set; } = new ObservableCollection();
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”>

</dxlc:LayoutItem>
viewmodel代码:

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

结果展示

图片


版权声明:本文为zls365365原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。