.NET/C# Binding Custom DependencyProperty to ViewModel Property

Consider the following scenario:

  • UserControl with a custom DependencyProperty
  • ViewModel with an exposed property (using INotifyPropertyChanged)

Goal: create two-way data binding between these two properties (i.e., ViewModel property gets updated if DependencyProperty changes and vice versa)

ViewModel (implements INotifyPropertyChanged):

  private string _someProperty;
 
  public string SomeProperty
  {
    get { return _someProperty; }
    set
    {
      _someProperty = value;
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs("SomeProperty"));
    }
  }

UserControl (class “MyUserControl”):

  public static readonly DependencyProperty DemoProperty = 
    DependencyProperty.Register(
      "Demo", typeof(string), typeof(MyUserControl), 
        new FrameworkPropertyMetadata() { 
          PropertyChangedCallback = OnDemoChanged, 
            BindsTwoWayByDefault = true });
 
  public string Demo
  {
    get { return this.GetValue(DemoProperty ); }
    set { this.SetValue(DemoProperty , value); }
  }
 
  private static void OnDemoChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  {
    if (e.OldValue != e.NewValue)
    {
      // code to be executed on value update
    }
  }

Setting up the data binding (e.g., in a Window assuming that it exposes MyViewModel as DependencyProperty and DataContext is set accordingly):

  <local:MyUserControl Demo="{Binding MyViewModel.SomeProperty}"/>

Notes:

  • default binding mode is set to BindsTwoWayByDefault

8 thoughts on “.NET/C# Binding Custom DependencyProperty to ViewModel Property

  1. Sorry, can’t find the code anymore :(… hope the provided snippets are still helpful!

  2. It is pretty good, but …
    … it is designed against encapsulation paradigm.
    Everywhere you use this control you have to remember to bind DependencyProperty to ViewModel property. Programmer using YourUserControl will not know what have to be done.

  3. Hi

    What happens however in OnDemoChanged? The datacontext is not static and therefore cannot be accessed – how can you update it? What listens to the viewmodel and updates the DP when the VM changes?

    Thanks,
    Ian

  4. Hi Ian,

    It’s been a while I wrote this, but I remember correctly the data binding takes care of updating. I don’t see why you would need the data context; this example is about synchronising a property. In OnDemoChanged, you write code that should be executed whenever the value changes; could be empty if you are happy with just updating the value.

    Thanks,
    Dominik

Comments are closed.