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
提取码:点击在看后请添加小编微信zls20210502获取。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有