How to bind to a WPF dependency property when the datacontext of the page is used for other bindings? (Simple question)
Asked
Active
Viewed 4.9k times
19
-
1Are you asking for something other than what you find when you search Google for "WPF databinding"? – Matt Hamilton Apr 21 '09 at 09:46
-
3I 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 Answers
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:

Community
- 1
- 1

Thomas Bratt
- 48,038
- 36
- 121
- 139
-
Does this automatically provide change notification whenever `Test` is changed through code? – Kos Jul 23 '12 at 12:25
-
-
1Can I do this with User Control? I tried the same thing but nothing happened... :( Maybe I'm missing something.. – Jack Frost Feb 09 '16 at 01:36
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