Having this in XAML:
<UserControl x:Class="Example"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
>
<Grid x:Name="RootPanel">
</Grid>
</UserControl>
how to get an equivalent of this in a code-behind:
public Example()
{
InitializeComponent();
this.RootPanel.DataContext = this;
}
There are many examples of how to bind object's data context to it's own self, e.g.
DataContext="{Binding RelativeSource={RelativeSource Self}}"
or how to bind a property to a property in the parent:
SomeOtherText="{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"
but I couldn't find an answer on how to bind to the parent itself.
You can bind to the parent UserControl
using a relative source binding.
<Grid x:Name="RootPanel" DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Example}}}">
The relative source will set the source of the binding to the Example
parent control.
By default, bindings inherit the data context specified by the DataContext property, if one has been set. However, the RelativeSource property is one of the ways you can explicitly set the source of a Binding and override the inherited data context.
The Path
is empty in this case, which will not bind to a specific property, but the control itself.
To bind to an entire object, you do not need to specify the Path property. For more information, see "Specifying the Path to the Value" in Data Binding Overview.