SuMau
SuMau

Reputation: 87

Instantiating a class that inherits INotifyPropertyChanged

I have a very simple class that has a single property and which inherits INotifyPropertyChanged:

class SimpleClass:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _property;
    public string Property
    {
        get { return _property; }
        set
        {
            _property = value; 
            PropertyChanged(this, new PropertyChangedEventArgs"Property"));
        }
    }
}

I try to instantiate a SimpleClass object in the constructor for a WPF Window but I get the following TargetInvocationException: "Exception has been thrown by the target of an invocation". If I remove the INotifyPropertyChange inheritance (and any reference to the PropertyChanged event) then I don't get the error and my project runs without any problems. Any ideas why?

Cheers

Upvotes: 0

Views: 571

Answers (3)

Chris Shain
Chris Shain

Reputation: 51369

Nothing in this code is obviously causing that error. We'd need more information to be sure what's going on. The hints you gave about INotifyPropertyChanged, however, lead me to believe its that your PropertyChanged event is null, and you don't have a null check around it. You either need to add the null check:

    set
    {
        _property = value; 
        if (PropertyChanged != null)
          PropertyChanged(this, new PropertyChangedEventArgs"Property"));
    }

or ensure that the event is never null:

public event PropertyChangedEventHandler PropertyChanged = (s, e) => { };

Upvotes: 1

Dessus
Dessus

Reputation: 2177

Try removing the brackets () after the class name:

public class SimpleClass:INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private string _property;
    public string Property
    {
        get { return _property; }
        set
        {
            _property = value; 
            PropertyChanged(this, new PropertyChangedEventArgs("Property"));
        }
    }
}

Upvotes: 0

John Gardner
John Gardner

Reputation: 25146

You aren't checking for null on PropertyChanged.

if nobody is listening, then it will be null. most people protect for the event listeners to change during the event, as well:

var listeners = PropertyChanged;
if (listeners != null)
    listeners(this, new PropertyChangedEventArgs("Property");

Upvotes: 4

Related Questions