简体   繁体   English

WPF列表框绑定-SelectedItem保持为空

[英]WPF Listbox binding - SelectedItem remains null

I am playing around with MVVM and binding. 我在玩MVVM和绑定。 More specifically a ListBox that shows a collection of objects: 更具体地说,一个ListBox显示了一个对象集合:

<ListBox ItemsSource="{Binding Scouts}" SelectedItem="{Binding SelectedScout, Mode=TwoWay}/>

In my ViewModel it looks like this: 在我的ViewModel中,它看起来像这样:

private ObservableCollection<Scout> scouts;
    private Scout selectedScout;

    public Scout SelectedScout
    {
        get { return selectedScout; }
        set
        {
            OnPropertyChanged("SelectedScout");
            value = selectedScout;
        }
    }

    public ObservableCollection<Scout> Scouts
    {
        get { return scouts; }
        set
        {
            OnPropertyChanged("Scouts");
            scouts = value; 
        }
    }

Now, the ListBox shows the Items in the Collection just fine, but what I want to do is click an item in the Box, and then show further details on that item in a TextBox. 现在,ListBox可以很好地显示Collection中的项目,但是我要做的是单击Box中的项目,然后在TextBox中显示该项目的更多详细信息。 I figured I would bind the ListBox' SelectedItem property to a Selected-property in my ViewModel (as shown above) and bind the property to the TextBox like so: 我以为可以将ListBox的SelectedItem属性绑定到ViewModel中的Selected-property(如上所示),然后将该属性绑定到TextBox,如下所示:

<TextBox Text="{Binding SelectedScout.Id}"/>

But it doesn't work. 但这是行不通的。 The TextBox remains blank when I select an item in the ListBox, and I figure it's because my SelectedScout property remians null. 当我在列表框中选择一个项目时,TextBox保持空白,因为我的SelectedScout属性为null。

I have been struggling with this problem for a while now, and I just can't seem to find the soloution. 我已经为这个问题苦苦挣扎了一段时间了,我似乎找不到这种解决方法。 I don't know what I am missing. 我不知道我在想什么。

Thank you in advance for your help. 预先感谢您的帮助。

**EDIT: I solved the problem. **编辑:我解决了这个问题。 Thank you for your answers, but the mistake was in this line: 感谢您的回答,但错误出在此行:

 public Scout SelectedScout
    {
        get { return selectedScout; }
        set
        {
            OnPropertyChanged("SelectedScout");
            *value = selectedScout;*
        }
    }

Where it should, of course, be: 当然应该在哪里:

selectedScout = value;

I feel really stupid now. 我现在真的很傻。 Thank you for your help. 谢谢您的帮助。

** **

Binding list of objects with XAML 使用XAML绑定对象列表

This is proper example for insert update delete selected index. 这是插入更新,删除所选索引的正确示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM