How to bind to a WPF dependency property when the datacontext of the page is used for other bindings?

Thomas Bratt picture Thomas Bratt · Apr 21, 2009 · Viewed 46.5k times · Source

How to bind to a WPF dependency property when the datacontext of the page is used for other bindings? (Simple question)

Answer

Thomas Bratt picture Thomas Bratt · Apr 21, 2009

The datacontext of the element needed to be set.

XAML:

<Window x:Class="WpfDependencyPropertyTest.Window1" x:Name="mywindow">
   <StackPanel>
      <Label Content="{Binding Path=Test, ElementName=mywindow}" />
   </StackPanel>
</Window>

C#:

public static readonly DependencyProperty TestProperty =
        DependencyProperty.Register("Test",
                                    typeof(string),
                                    typeof(Window1),
                                    new FrameworkPropertyMetadata("Test"));
public string Test
{
   get { return (string)this.GetValue(Window1.TestProperty); }
   set { this.SetValue(Window1.TestProperty, value); }
}

Also see this related question:

WPF DependencyProperties