I'm implementing INotifyPropertyChanged in a 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'm using it as follows:
RaisePropertyChanged("Name");
I'm getting a NullReferenceException while the arguments, "this" and the handler are NOT null. Can anyone shed some light on this?
Thanks.
-> Full stacktrace of the exception: http://pastebin.com/bH9FeurJ
UPDATE The exception occurs when I overwrite an instance of the class which contains this property. 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'm using this DummyPerson
and its Name
property to databind to the UI. The second and all following attempts thereafter result in the NullReferenceException
.
The exception isn't raised in your sample code, it is raised in one of the subscribed event handlers. Go through it step by step in debugger or turn on the switch "Thrown" for "Common Language Runtime Exceptions" in "Debug" - "Exceptions" menu of Visual Studio. Then you will be able to find out the reason.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With