Bind to Property of Window or UserControl Using RelativeSource

By Michael Detras

Some people set a Window or UserControl's DataContext property to itself to easily bind to its properties. If the DataContext is set to another object, then we can use RelativeSource to bind to the Window or UserControl's properties.

Here is an example of binding a TextBox's Text property to SomeProperty of the Window.

<TextBox Text="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}, Path=SomeProperty}" />

If the control is not a Window, then just change the AncestorType to the type of Control, like UserControl or your custom control.

Related FAQs

Shows an example on how to bind to a property of a UI element using XAML.
Bind properties to your control without the XAML.
This shows how to bind a dependency property to more than 1 binding source using multi-binding.
Bind to Property of Window or UserControl Using RelativeSource  (3268 Views)