C# 使用MVVM更改选择事件
我有一个列表框,其中包含人员列表。 当用户单击某个项目时,viewModel应将currentPerson对象设置为用户单击的对象 为此,我必须使用ViewModel,因此在MainWindow.xaml.xs中没有代码。有什么办法解决这个问题吗?很简单: 向ViewModel添加属性C# 使用MVVM更改选择事件,c#,wpf,mvvm,listbox,listitem,C#,Wpf,Mvvm,Listbox,Listitem,我有一个列表框,其中包含人员列表。 当用户单击某个项目时,viewModel应将currentPerson对象设置为用户单击的对象 为此,我必须使用ViewModel,因此在MainWindow.xaml.xs中没有代码。有什么办法解决这个问题吗?很简单: 向ViewModel添加属性CurrentPerson,并将其绑定到列表框的SelectedItem属性 大概是这样的: 视图模型: public Person CurrentPerson { get { return _curren
CurrentPerson
,并将其绑定到列表框的SelectedItem
属性
大概是这样的:
视图模型:
public Person CurrentPerson
{
get { return _currentPerson; }
set
{
if(value == _currentPerson) return;
_currentPerson = value;
NotifyOfPropertyChange("CurrentPerson");
}
}
视图:
+1:我通常绑定到SelectedValue,但我记得SelecteItem属性有问题。@Baboon:这不是个好主意SelectedItem
是整个对象SelectedValue
是由SelectedValuePath
定义的对象的一部分。如果您过去在SelectedItem
方面遇到了一些问题,那么很可能是其他问题SelectedItem
确实是正确的属性。还有一个问题:VS告诉我它无法解决NotifyOfPropertyChange(“CurrentPerson”)。这只是一个引发PropertyChanged
事件的小助手方法。您可以通过任何方式将NotifyOfPropertyChange更改为OnPropertyChange,这样可以吗?
<ListBox SelectedItem="{Binding CurrentPerson}" ...>