views:

123

answers:

2

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.

+1  A: 

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.

Martin Harris
+2  A: 

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.

Thomas Levesque
I think I get it now. So are they only used in custom user controls or can they be used anywhere else? thanks
HAdes
You can use them in any class that inherits from DependencyObject, whether or not it is a control. You can also create *attached* dependency properties in any class, even if it doesn't inherit from DependencyObject. This is often used to extend the behavior of existing controls without resorting to inheritance.
Thomas Levesque
ok thanks, i'll have a play around
HAdes