C# 在多个窗口上绑定到同一属性不会';行不通

C# 在多个窗口上绑定到同一属性不会';行不通,c#,wpf,mvvm,C#,Wpf,Mvvm,在开发多窗口wpf应用程序时,我遇到了一个相当令人困惑的问题 有两个窗口,Main窗口和Second窗口。两者的代码都非常简单: 主窗口: <Button Content="Change Property to 5" Click="ChangeProperty" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" /> 以及实现INotifyPropertyChanged的视图模型类: clas

在开发多窗口wpf应用程序时,我遇到了一个相当令人困惑的问题

有两个窗口,Main窗口和Second窗口。两者的代码都非常简单: 主窗口:

<Button Content="Change Property to 5" Click="ChangeProperty" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" />
以及实现INotifyPropertyChanged的视图模型类:

class ViewModel : INotifyPropertyChanged
{
    private MyClass _instance;
    public MyClass InstanceOfMyClass 
    {
        get
        {
            return _instance;
        }
        set
        {
            _instance = value;
            OnPropertyChanged("InstanceOfMyClass");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
class MyClass
{
    public int value { get; set; }
}
当我单击按钮时,我希望文本块将其文本更改为5。 启动时正确加载数字“3”。当我创建
MyClass
的新实例并在我的
ViewModel
中将其设置为
InstanceOfMyClass
时,该窗口也会刷新

但是,当我按下按钮时——或者更奇怪的是,当我临时存储
InstanceOfMyClass
时,将其设置为
null
,并使用保存的变量重新分配它时——什么都没有发生

知道为什么吗


提前谢谢

MyClass
中实现
INotifyPropertyChanged
,然后重试。在
ChangeProperty
中更改
属性,该属性不会通知视图有关更改的信息

或者,您也可以尝试将
ChangeProperty
重写为以下内容:

vm.InstanceOfMyClass = new MyClass() { value = 7 };

就我所知,这两种方法都可以解决问题。

谢谢!所以这与第二个窗口无关。
class ViewModel : INotifyPropertyChanged
{
    private MyClass _instance;
    public MyClass InstanceOfMyClass 
    {
        get
        {
            return _instance;
        }
        set
        {
            _instance = value;
            OnPropertyChanged("InstanceOfMyClass");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}
class MyClass
{
    public int value { get; set; }
}
vm.InstanceOfMyClass = new MyClass() { value = 7 };