我认为你一定做错了你在帖子中没有提到的事情。以下代码按预期工作,并将 MyTestPropertyName 打印到控制台窗口。
public partial class MainWindow : Window
{
public MainWindow()
{
DataContext = new MyViewModel();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MyViewModel viewModel = DataContext as MyViewModel;
viewModel.PropertyChanged += MyPropertyChangedEventHandler;
viewModel.NotifyPropertyChanged();
}
private void MyPropertyChangedEventHandler(object sender, PropertyChangedEventArgs e)
{
Console.WriteLine(e.PropertyName);
}
}
public class MyViewModel : INotifyPropertyChanged
{
public void NotifyPropertyChanged()
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs("MyTestPropertyName"));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
应该注意的是,这是一个糟糕的设计,并且仅作为概念证明而设计,您确实可以在代码隐藏中订阅 ViewModel 上的事件。