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

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

James.TCG

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值