19

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

Giffyguy
  • 20,378
  • 34
  • 97
  • 168
Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139
  • 1
    Are you asking for something other than what you find when you search Google for "WPF databinding"? – Matt Hamilton Apr 21 '09 at 09:46
  • 3
    I was looking for a working example, where the datacontext of the page is already used for the other bindings. As it turns out, the datacontext of the the element needed to be set to the page itself. I'll post code and edit the question, if required. – Thomas Bratt Apr 21 '09 at 17:35

2 Answers2

34

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

Community
  • 1
  • 1
Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139
11

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
  • 73,686
  • 17
  • 161
  • 157