HAdes
HAdes

Reputation: 17033

What's the point in setting up dependency properties, when PropertyChangedEventHandler does the job?

Currently I have use the following approach to setup change notification on any of my properties that I bind to in xaml:

    class MyClass : INotifyPropertyChanged
{
    string name;

    public string Name
    {
        get { return name; }
        set
        {
            name = value;
            NotifyPropertyChanged("Name");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    public void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

However, I've seen that to implement a dependency property I need to do stuff like registering it and setting callbacks etc, which in turn will just end up calling the above code.

So what's the point of setting all the extra boiler plate stuff for dependency properties when I can just use the above approach?

Thanks.

Upvotes: 1

Views: 326

Answers (2)

Thomas Levesque
Thomas Levesque

Reputation: 292615

Dependency properties can be the target of a binding, whereas regular CLR properties can't. That's why the properties of a control (binding target) are usually dependency properties, whereas the properties of a model or ViewModel class (binding source) are not.

Upvotes: 3

Martin Harris
Martin Harris

Reputation: 28617

What you are doing is correct (assuming I understand it correctly) dependency properties are not for the things you bind to in the model they are for the properties in controls that the model will be bound to - for example the Text property in a text box.

There are a number of reasons to use them in your custom controls, not least of which is the automatic plumbing that comes with them so that they will correctly bind to a property declared as in your example.

Upvotes: 1

Related Questions