Strange NullReferenceException with implementation of INotifyPropertyChanged

I implement INotifyPropertyChanged in the base class as follows:

public class NotifyPropertyChangedBase : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; protected virtual void RaisePropertyChanged(string propertyName) { var propChangedHandler = PropertyChanged; if (propChangedHandler != null) { var args = new PropertyChangedEventArgs(propertyName); propChangedHandler(this, args); } } } 

I use it as follows:

 RaisePropertyChanged("Name"); 

I get a NullReferenceException, while the arguments to "this" and the handler are NOT null. Can anyone shed some light on this?

Thanks.

-> Full exception stacking: http://pastebin.com/bH9FeurJ

UPDATE An exception occurs when I overwrite an instance of a class that contains this property. A simplified example:

 public class Person : INotifyPropertyChanged { private string _name; public string Name { get { return _name; } set { _name = value; RaisePropertyChanged("Name"); } } // More properties etc. } 

-snip -

 public class ViewModel { private Person _dummyPerson; public Person DummyPerson { get { return _dummyPerson; } set { _dummyPerson = value; RaisePropertyChanged("DummyPerson"); } } public void Foo() { DummyPerson = new DummyPerson(); // this line throws the NRE, strangly enough the very FIRST time it works fine } } 

-snip -

I use this DummyPerson property and its Name to bind data to the user interface. After this, the second and all subsequent attempts will result in a NullReferenceException .

+6
source share
3 answers

I had this error for a while, but now I solved it (although it may be a different reason in my code) - I was (rather stupid) without checking the null value in one of my IValueConverter implementations, (and for some reason the code would not allow me to enter this code) and threw an exception, because null was taken as a value.

+1
source

An exception does not occur in your sample code, it occurs in one of the signed event handlers. Go it step by step in the debugger or enable the "Abandoned" switch for "Exclude the total runtime of the language" in the menu "Debug" - "Exceptions" in Visual Studio. Then you can find out the reason.

+3
source

Looking at the stack trace, it is clear that a NullReferenceException does not rush here at all; it actually throws deeper at the address:

  GalaSoft.MvvmLight.Command.RelayCommand`1.Execute(Object parameter) 

In fact, the dependency of one of the event listeners is incorrect.

Also: I was not sure that the stack trace convention you are using is β€œgrowth” or β€œgrowth”. As soon as I saw that the method just above the yoir method was a delegate call:

 System.ComponentModel.PropertyChangedEventHandler.Invoke(Object sender, PropertyChangedEventArgs e) 

... it was clear that the stack was really growing up.

+1
source

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


All Articles