INotifyPropertyChanged - event remains invalid

I am trying to implement the following INotifyPropertyChanged extension:

Automatically INotifyPropertyChanged (accepted answer) http://ingebrigtsen.info/2008/12/11/inotifypropertychanged-revisited/

But I can not understand why my PropertyChanged EventHandler remains null. :(

I made a very simple WPF application to test it, here is my XAML code:

<StackPanel Orientation="Vertical"> <TextBox Text="{Binding Path=SelTabAccount.Test, UpdateSourceTrigger=PropertyChanged}"></TextBox> <TextBox Text="{Binding Path=SelTabAccount.TestRelated, UpdateSourceTrigger=PropertyChanged}"></TextBox> </StackPanel> 

And my code is:

 public partial class MainWindow : Window, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private TabAccount _selTabAccount; public TabAccount SelTabAccount { get { return _selTabAccount; } set { _selTabAccount = value; PropertyChanged.Notify(() => this.SelTabAccount); } } public MainWindow() { InitializeComponent(); SelTabAccount = new TabAccount() { Test = "qwer", TestRelated = "" }; } } public partial class TabAccount : INotifyPropertyChanged { private string _test; public string Test { get { return _test; } set { _test = value; PropertyChanged.Notify(() => this.Test); PropertyChanged.Notify(() => this.TestRelated); } } public event PropertyChangedEventHandler PropertyChanged; } public partial class TabAccount { private string _testRelated; public string TestRelated { get { _testRelated = Test + "_Related"; return _testRelated; } set { _testRelated = value; PropertyChanged.Notify(() => this.TestRelated); } } } 

In the code behind you will see one class (its partial for just random testing) with 2 properties that should notify the property change, but nothing happens.

NotificationExtension is a copy and paste of the links provided above, and is located in an external cs file.

I also tried to make a sample with the "normal" implementation of INotifyPropertyChanged, and this works as expected, but I cannot do this with this extension class.

I hope you help me figure it out. Thanks in advance.

+4
source share
2 answers

Linking will only work when you provide some data source to visual objects. If you do not provide any data source and do not want to delve into the properties, the binding will not work.

Under the MainWindow constructor, set the DataContext property of the window to the data source. For instance:

  public MainWindow() { InitializeComponent(); // your property setups this.DataContext = this; } 

Essentially, this makes the MainWindow properties available for binding to the visual tree of MainWindow elements.

+4
source

You will need to set the DataContext of the window. You can do this in the construnctor window after initializecomponent.

 this.DataContext = this; 

this should do the trick.

thanks

+1
source

Source: https://habr.com/ru/post/1499344/


All Articles