ListBox等控件的SelectedItem,SelectedValue,SelectedValuePath属性详解

引言

初学WPF可能会对诸如ComboBox、ListBox等集合控件的当前选择项的绑定有所疑惑,控件提供了两个可绑定对象:SelectedItem\SelectedValue,同时还有DisplayMemberPath\SelectedValuePath。本节来讲述一下它们的设计意图和用法。

1、SelectedItem与DisplayMemberPath

在Winform中,我们经常用到SelectedItem,它表示的就是当前控件的选择项。若你给控件的Itemsource绑定到集合List<Person>、ObservableCollection<Person>等,当前SelectedItem即为某一个Person,这样的说明略显苍白冗余。记住此刻我们SelectedItem指代的是整个Person实例。

DisplayMemberPath 可以进一步指定控件中显示Person的有一个属性。如果不设置DisplayMemberPath,控件会调用Person的ToString()方法,显示结果。

cs 复制代码
<ListBox 
    Name="PersonListBox"
    SelectedIndex="0"
    SelectedItem="{Binding SelectedPerson}"
    DisplayMemberPath="Name"
    ItemsSource="{Binding Persons}"/>

2、SelectedValue与SeletedValuePath

WPF除了绑定ViewModel的属性,还可以绑定xmal元素的属性,当我们需要绑定当前选择项Person时我们可以通过ElementName查找等方法找到比如ComboBox、ListBox的SelectedItem。如果需要关注Person的某一个属性,则要写成SelectedItem.ID、SelectedItem.Name等形式。

cs 复制代码
<TextBlock Text="{Binding ElementName=PersonListBox,Path=SelectedItem.Name}"/>

现在增加需求,我们想要在ViewModel中直接观察当前选中Person的某一个属性 ,比如Name\ID等,或则后台通过更改当前CurrentPersonID实现当前选项的更改时,可能就比较麻烦,此时WPF为我们提供的SelectedValue和SelectedValuePath就派上用场了。

SelectedValuePath用来指定你要对外绑定的Person属性名称,SelectValue用来绑定该属性。

cs 复制代码
//vm
public string CurrentPersonID{get;set;}

//xaml
<ListBox 
    Name="PersonListBox"
    SelectedIndex="0"
    SelectedItem="{Binding SelectedPerson}"
    SelectedValue="{Binding CurrentPersonID}"
    SelectedValuePath="ID"
    ItemsSource="{Binding Persons}"/>

<TextBlock Text="{Binding CurrentPersonID}"/>

注:SelectedValue是支持双向绑定通知的

相关推荐
czhc114007566321 小时前
wpf 511 封装通信类 半导体协议:SECS
wpf
lingxiao168881 天前
WPF数据采集和监控(Industrial)
wpf
雨浓YN1 天前
GKTGD 工业监控系统-02MySQL 数据库技术文档(类库:NET8_SQLData)
数据库·wpf
雨浓YN1 天前
GKTGD 工业监控系统-03SQLite 数据库技术文档(类库:NET8_SQLData)
数据库·wpf
deokoo1 天前
.NET WPF 工程离线迁移完整指南:告别“包降级”与assets文件缺失
wpf
雨浓YN1 天前
GKTGD 工业监控系统-04MySQL 与 SQLite 数据库对比(类库:NET8_SQLData)
数据库·sqlite·wpf
Bofu-2 天前
【内存测试】06-WPF 读取 SMBIOS 实现内存规格自动检测
wpf·p/invoke·windows api·smbios·内存检测·dimm·硬件信息读取
Bofu-2 天前
【Storage存储测试】07-WPF 通过 WMI + NVMe SMART 实现 SSD 规格自动验证
wpf·nvme·wmi·smart·ssd检测
Bofu-2 天前
【键盘测试】05-WPF 可视化键盘布局配置 + 全局钩子按键检测实战
wpf·键盘测试·全局键盘钩子·scancode·组合键检测
bugcome_com2 天前
WPF 路径动画完全指南:自绘制控件实战
wpf