转载:ListBox的SelectedValue和SelectedItem的区别

原文:http://www.beacosta.com/blog/?p=9

What is the difference between SelectedValue and SelectedItem?

When they are used by themselves, these two properties are very similar. The need for both and the difference between the two becomes apparent when SelectedValuePath is also set.

For example, consider our well-known GreekGods data source. I set the DataContext of the StackPanel to be that collection through code:

    GreekGods items;
    items = new GreekGods();
    mainStackPanel.DataContext = items;

And used an empty Binding to bind that collection to the ListBox. I know that I want to select the GreekGod with description “Messenger of the Gods” (even though I am only displaying the Name of each God). This is when SelectedValuePath becomes useful. Each item in the ListBox is a GreekGod object, so by setting SelectedValuePath to “Description” I am able to drill down into the Description property of each GreekGod. Then I just have to set SelectedValue to the description I am looking for and the item becomes selected.

    <StackPanel Name=”mainStackPanel”>
        <ListBox ItemsSource=”{Binding}” DisplayMemberPath=”Name” SelectedValue=”Messenger of the Gods” SelectedValuePath=”Description” Name=”listBox1″ (…) />
    </StackPanel>

// 注意这里可以用一个空的绑定,选择了GreekGod的Name作为DisplayMember,选择Description作为SelectedValue的选择字段,并且这里选择了Description的内容是"Messenger of the Gods"的那个Item。

The difference between SelectedValue and SelectedItem should be obvious now. SelectedValue returns the string it was set to (”Messenger of the Gods”), while SelectedItem returns the actual GreekGod object with that description.

    string messengerOfGods = (string)(listBox1.SelectedValue);
    GreekGod hermes = (GreekGod)(listBox1.SelectedItem);

SelectedValue is particularly useful when only part of your item is stored in the model you are data binding to. In this scenario, you would data bind the SelectedValue property to the partial information in your model but the ListBox can show a lot more information about that item.

If you have ideas of how to combine these two properties in one, we would love to hear it.

SelectedValueSample.png

Here you can find the VS project with this sample code. Put a breakpoint in the handler for the button click to inspect the values of SelectedValue and SelectedItem when the button is clicked. This works with September CTP WPF bits.

posted on 2008-10-20 15:52 cutebear 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/bear831204/archive/2008/10/20/1313538.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值