如何通知`DataContext`被替换?

时间:2014-11-03 11:26:49

标签: c# wpf mvvm data-binding datacontext

如何通知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));
    }   

但它不起作用,不知道为什么......

0 个答案:

没有答案