选择使用MVVM更改事件

Goo*_*oot 6 c# wpf listbox listitem mvvm

我有一个包含人员列表的列表框.当用户单击某个项时,viewModel应将currentPerson对象设置为用户单击的Object.

我必须为此使用ViewModel,因此MainWindow.xaml.xs中没有代码.任何想法如何解决这个问题?

Dan*_*rth 6

这很简单:

将属性添加CurrentPerson到ViewModel并将其绑定到SelectedItemListBox 的属性.

像这样的东西:

查看型号:

public Person CurrentPerson
{
    get { return _currentPerson; }
    set
    {
        if(value == _currentPerson) return;
        _currentPerson = value;

        NotifyOfPropertyChange("CurrentPerson");
    }
}
Run Code Online (Sandbox Code Playgroud)

视图:

<ListBox SelectedItem="{Binding CurrentPerson}" ...>
Run Code Online (Sandbox Code Playgroud)

  • @Baboon:那不是个好主意.`SelectedItem`是整个对象.`SelectedValue`是`SelectedValuePath`定义的对象的一部分.如果你在过去遇到过`SelectedItem`的问题,那很可能就是别的了.`SelectedItem`肯定是正确的属性. (2认同)