MVVM:绑定到 ListBox.SelectedItem?

编程入门 行业动态 更新时间:2024-10-19 18:23:56
本文介绍了MVVM:绑定到 ListBox.SelectedItem?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何将视图模型属性绑定到 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?

本文发布于:2023-11-06 14:11:54,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563910.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:绑定   MVVM   SelectedItem   ListBox

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!