Yurii N.
Yurii N.

Reputation: 5703

Difference between dependency properties in WPF

I have two implementations of dependency properties in WPF. First, that I found in internet:

public class TestClass : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    private string _test;

    public string Test
    {
       get
       {
           return _test;
       }
       set
       {
           _test = value;
           OnPropertyChanged(nameof(Test))
       }
    }
}

And second, from propdp snippet:

public class TestClass
{
    public string Test
    {
         get { return (string)GetValue(TestProperty); }
         set { SetValue(TestProperty, value); }
    }
    public static readonly DependencyProperty TestProperty =     
        DependencyProperty.Register("Test", 
        typeof(string), 
        typeof(TestClass), 
        new PropertyMetadata(string.Empty));
}

What is the difference between them? What should I use?

Upvotes: 0

Views: 305

Answers (1)

Vadim Martynov
Vadim Martynov

Reputation: 8902

You can bind to the DependencyProperty some value which can implement INotifyPropertyChanged. For example, if you write:

<TextBox Content="{Binding FirstName}" />

then Content is a dependency property which will react to the binding source changing.

The main difference is, that the value of a normal .NET property is read directly from a private member in your class, whereas the value of a DependencyProperty is resolved dynamically when calling the GetValue() method that is inherited from DependencyObject.

When you set a value of a dependency property it is not stored in a field of your object, but in a dictionary of keys and values provided by the base class DependencyObject. The key of an entry is the name of the property and the value is the value you want to set.

via

You should use simple properties in your ViewModels which you'll bind to the dependency properties in WPF objects (Content, Background, IsChecked and many other include DP which you will define in your custom user controls).

Upvotes: 2

Related Questions