我正在尝试将View中的CheckBox绑定到ViewModel中的属性。我正在尝试订阅单个ViewModel属性的更改。
我在自定义类上实现了INotifyPropertyChanged,但是我的处理程序方法从未被调用。
我已经包含了View(XAML),ViewModel和自定义用户类的基本示例。
public class HomeViewModel: ViewModelBase
{
public HomeViewModel()
{
this.selectedUser = new usersVM();
this.selectedUser.PropertyChanged += propChangedHandler;
}
private void propChangedHandler(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "superuser") // <-- breakpoint here
{
}
}
private usersVM _selectedUser;
public usersVM selectedUser
{
get { return this._selectedUser; }
set
{
if (this._selectedUser != value)
{
this._selectedUser = value;
this.RaisePropertyChanged("selectedUser");
}
}
}
}
public class usersVM : INotifyPropertyChanged
{
public usersVM()
{
this.hasChanges = false;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private int _superuser;
public int superuser
{
get
{
return this._superuser;
}
set
{
if (value != this._superuser)
{
this._superuser = value;
NotifyPropertyChanged("username");
}
}
}
<CheckBox Margin="0,0,8,0" Content="SuperUser" IsChecked="{Binding superuser}" DataContext="{Binding selectedUser}" />
我的Hadler方法中有一个断点,试图验证事件的处理时间,但从未调用过。
如何在ViewModel中正确实现INotifyPropertyChanged并订阅这些事件?
答案 0 :(得分:0)
从当前selectedUser值中分离PropertyChanged事件处理程序并将其附加到新的值,如下所示:
private usersVM _selectedUser;
public usersVM selectedUser
{
get { return _selectedUser; }
set
{
if (_selectedUser != value)
{
if (_selectedUser != null)
{
_selectedUser.PropertyChanged -= propChangedHandler;
}
_selectedUser = value;
if (_selectedUser != null)
{
_selectedUser.PropertyChanged += propChangedHandler;
}
RaisePropertyChanged("selectedUser");
}
}
}