如何将视图模型属性绑定到 ListBox.SelectedItem 属性?
How do I bind a view model property to the ListBox.SelectedItem property?
我创建了一个简单的 MVVM 演示来尝试解决这个问题.我的视图模型具有以下属性:
I have created a simple MVVM demo to try to figure this one out. My view model has these properties:
private ObservableCollection<DisneyCharacter> p_DisneyCharacters; public ObservableCollection<DisneyCharacter> DisneyCharacters { get { return p_DisneyCharacters; } set { p_DisneyCharacters = value; base.FirePropertyChangedEvent("DisneyCharacters"); } } private DisneyCharacter p_SelectedItem; public DisneyCharacter SelectedItem { get { return p_SelectedItem; } set { p_SelectedItem = value; base.FirePropertyChangedEvent("SelectedItem"); } }我想将 SelectedItem 属性绑定到列表框中选定的项目.这是列表框的 XAML:
I want to bind the SelectedItem property to the item selected in the list box. Here is the XAML for the list box:
<ListBox ItemTemplate="{StaticResource MasterTemplate}" ItemsSource="{Binding Path=DisneyCharacters}" SelectedItem="{Binding Path=Selectedtem, Mode=TwoWay}" HorizontalAlignment="Stretch" />这是我的问题:当我更改列表框中的选择时,视图模型 SelectedItem 属性没有更新.
Here is my problem: The view model SelectedItem property isn't being updated when I change the selection in the list box.
我做了一个测试,我临时用 SelectedIndex 属性替换了视图模型的 SelectedItem 属性,并将其绑定到 ListBox.SelectedIndex 属性.该属性更新得很好——只是我无法使用的 SelectedItem 属性.
I did a test where I temporarily replaced the view model SelectedItem property with a SelectedIndex property, and I bound that to the ListBox.SelectedIndex property. That property updated fine--it's just the SelectedItem property that I can't get to work.
那么,如何修复 SelectedItem 绑定?感谢您的帮助.
So, how do I fix the SelectedItem binding? Thanks for your help.
推荐答案嗯,就是这样,就像生命一样重要.在 XAML 中.我绑定到视图模型属性Selectedtem".不幸的是,实际名称是SelectedItem".所以这段代码确实有效——我今天下午早些时候解决了这个问题,然后花了整个下午和整个晚上的时间在网上搜索,然后才发现拼写错误.
Well, there it is, big as life. In the XAML. I am binding to a view model property "Selectedtem". Unfortunately, the actual name is "SelectedItem". So this code actually works--I solved the problem early this afternoon and then spent the rest of the afternoon and all evening scouring the web, before I noticed the spelling error.
我妻子在今天下午 3:00 告诉我,你知道,结果会是一件小事."所以它确实 - 一个丢失的字母I".好吧,至少我现在可以去睡觉了.
My wife told me at 3:00 this afternoon, "You know, it's going to turn out to be something small." And so it did--a missing letter "I". Well, at least I can go to bed now.
更多推荐
MVVM:绑定到 ListBox.SelectedItem?
发布评论