wpf - INotifyPropertyChanged.PropertyChanged 始终为 NULL

标签 wpf inotifypropertychanged

我知道我在这里做错了什么,但是什么。请大家看一下并指出我的错误。

单击按钮后,我将在文本框中看到“Peter”,但看不到“Jack”。

我的类(class)

namespace App
{
    class Person : INotifyPropertyChanged
    {
        private string name;
        public String Name
        {
            get { return name; }
            set { name = value; OnPropertyChanged("Name"); }
        }
    public Person()
    {
        Name = "Peter";
    }

    public void SetName(string newname)
    {
        Name = newname;
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private void OnPropertyChanged(string prop)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(prop));
        }
    }
}

}

我的 XAML

<Window x:Class="test.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:app="clr-namespace:App"
    Title="MainWindow" Height="400" Width="400">
<Grid>
    <Grid.Resources>
        <app:Person x:Key="person"/>
    </Grid.Resources>
    <TextBox  Width="100" Height="26" Text="{Binding Source={StaticResource person}, Path=Name, Mode=TwoWay}" />
    <Button Content="Button" Height="23"  Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>

还有我的代码隐藏

public partial class MainWindow : Window
{
    Person person;

    public MainWindow()
    {
        InitializeComponent();

        person = new Person();       
    }

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        person.SetName("Jack");
    }
}

谢谢。

最佳答案

您有两个 Person 实例。静态资源中PropertyChanged不为null

这并不是 StaticResources 的真正用途。摆脱静态资源,将绑定(bind)更改为:

{Binding Path=Name, Mode=TwoWay}

并将其添加到您的构造函数中:

DataContext = person;

关于wpf - INotifyPropertyChanged.PropertyChanged 始终为 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5754385/

相关文章:

WPF CollectionViewSource 多个 View ?

c# - WPF/C#网络浏览器youtube

c# - 如何从 ViewModel 中删除方法的执行 - Xamarin.Forms - MVVM

c# - 当属性在 C# 中只有 getter 时如何创建属性更改事件

c# - 使用反射获取 INotifyPropertyChanged 通知的属性的实际值?

wpf - 本地 WPF C# 编程

wpf - WPF打印-在WPF PrintDialog上自动设置打印机

wpf - XAML缩放问题

C# 无法从 'ref xxx' 转换为 'ref object'

Silverlight AutoCompleteBox NotifyPropertyChanged 不更新屏幕