views:

4078

answers:

2

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

+2  A: 

In XAML:

Something="{Binding SomethingElse, ElementName=SomeElement}"

In code:

BindingOperations.SetBinding(obj, SomeClass.SomethingProperty, new Binding {
  Path = new PropertyPath(SomeElementType.SomethingElseProperty),  /* the UI property */
  Source = SomeElement /* the UI object */
});

Though usually you will do this the other way round and bind the UI property to the custom dependency property.

itowlson
A: 

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:

http://stackoverflow.com/questions/317973/wpf-dependencyproperties

Thomas Bratt