星期三, 十二月 27, 2006

SelectedValue和SelectedItem有什么不同?

SelectedValue和SelectedItem有什么不同?


http://www.beacosta.com/Archive/2005_10_01_bcosta_archive.html
当他们被分别使用时,这两个属性是很相象的.但当同时使用且设置了SelectedValuePath时,不同之处就显示出来了.

例如,考虑到我们熟悉的GreekGods数据源,我通过代码设置StackPanel的DataContext为这个集合:

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

且使用空的Binding绑定到ListBox的集合上.我想通过"Messenger of the Gods"描述来选择GreekGod(即使我只显示每个God的名字).这时SelectedValuePath就很有用了.每个ListBox的项都是一个GreekGod物件. 通过设置SelectedValuePath为"Description",我能够深入到每个GreekGod的Description属性.这样我只要设置SelectedValue为我所想要的描述就可以选择该项了.
    
        
ItemsSource="{Binding}" DisplayMemberPath="Name"
SelectedValue="Messenger of the Gods" SelectedValuePath="Description"
Name="listBox1" (...) />
    

SelectedValue和SelectedItem的不同就显而易见了.SelectedValue返回它所设置的字符串("Messenger of the Gods"),但是SelectedItem返回那个描述所指定的GreekGod对象.

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

当只需要绑定模型上的部分数据时,SelectedValue就很有用了.你可以绑定SelectedValue属性到你模型的部分信息上,而ListBox却能显示更多的信息.

如果你知道如何结合这两个属性为一个,请告诉我们.
If you have ideas of how to combine these two properties in one, we would love to hear it.

没有评论: