INotifyPropertyChanged.PropertyChanged is always NULL

I know that I am doing something wrong here, but what. Please look and indicate my mistake.

I will see “Peter” in my text box, but after clicking the “Jack” button there will be no.

My 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));
        }
    }
}

}

My 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>

And my codebehind

public partial class MainWindow : Window
{
    Person person;

    public MainWindow()
    {
        InitializeComponent();

        person = new Person();       
    }

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

Thank.

+5
source share
2 answers

You have two instances of Person. PropertyChanged is not null in a static resource

This is not what StaticResources are for. Get rid of the static resource, change the binding to:

{Binding Path=Name, Mode=TwoWay}

and add this to your constructor:

DataContext = person;
+6
source

- codebehind MainWindow , XAML

, , -

person = (Person)Resources["person"];
0

All Articles