如何通知DataContext
已被替换?假设我有UserControl
:
public partial class MyUserControl : UserControl {
...
void OnSomethingHappens_Change_DataContext () {
DataContext = new MyViewModelType();
}
}
当我呼叫OnSomethingHappens_Change_DataContext()
时,所有绑定都将停止运行。我目前的解决方法是实现INotifyPropertyChanged
:
public partial class MyUserControl : UserControl, INotifyPropertyChanged {
...
void OnSomethingHappens_Change_DataContext () {
DataContext = new MyViewModelType();
PropertyChanged(this, new PropertyChangedEventArgs("DataContext"));
}
public event PropertyChangedEventHandler PropertyChanged;
}
但制作UserControl
工具INotifyPropertyChanged
感觉很尴尬。我试过了:
void OnSomethingHappens_Change_DataContext () {
var oldDataContext = DataContext;
DataContext = new MyViewModelType();
OnPropertyChanged(new DependencyPropertyChangedEventArgs(DataContextProperty, oldDataContext, DataContext));
}
但它不起作用,不知道为什么......