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

data-bindingdependency-propertieswpf

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

Best Answer

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