当前位置: 首页 > news >正文

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()方法,显示结果。

<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等形式。

<TextBlock Text="{Binding ElementName=PersonListBox,Path=SelectedItem.Name}"/>

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

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

//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是支持双向绑定通知的


http://www.mrgr.cn/news/18939.html

相关文章:

  • pr瘦脸怎么操作?
  • CSS学习10
  • 内存卡乱码问题解析恢复方案
  • 渠道招商有哪些工作内容?可以通过什么途径获客!
  • Allure报告下载不同格式的文件
  • redis缓存和数据库通过延迟双删除实现数据一致性
  • 基于Bert-base-chinese训练多分类文本模型(代码详解)
  • 为什么说2025年是国自然申请最佳时机?
  • Centos根目录扩容Docker分区扩容最佳实践
  • MySQL备份与恢复
  • 鸿蒙开发占多列的瀑布流
  • 商务文件的八大翻译需求
  • 短剧APP遭遇DDoS攻击的解决方法
  • 代码随想录打卡第10天
  • 前端框架大观:探索现代Web开发的基石
  • 算法:当一系列数据经过四舍五入后,总和不再等于100%时
  • 图论题总结
  • 数据结构————单向链表
  • Kettle 锁表原因及解决办法【源码级分析】
  • Python数据分析实战,兰州市二手房市场深度分析