XAML binding not working on dependency property?

The dependency property declaration must look like this:

public static readonly DependencyProperty TestProperty =
    DependencyProperty.Register(
        nameof(Test),
        typeof(string),
        typeof(MyControl),
        new PropertyMetadata("DEFAULT"));

public string Test
{
    get { return (string)GetValue(TestProperty); }
    set { SetValue(TestProperty, value); }
}

The binding in the UserControl’s XAML must set the control instance as the source object, e.g. by setting the Bindings’s RelativeSource property:

<UserControl x:Class="WpfTest.MyControl" ...>
     <TextBlock Text="{Binding Test,
         RelativeSource={RelativeSource AncestorType=UserControl}}"/>
</UserControl>

Also very important, never set the DataContext of a UserControl in its constructor. I’m sure there is something like

DataContext = this;

Remove it, as it effectively prevents inheriting a DataContext from the UserConrol’s parent.

By setting Source = DataContext in the Binding in code behind you are explicitly setting a binding source, while in

<local:MyControl Test="{Binding MyText}" />

the binding source implicitly is the current DataContext. However, that DataContext has been set by the assignment in the UserControl’s constructor to the UserControl itself, and is not the inherited DataContext (i.e. the view model instance) from the window.

Leave a Comment