问题描述
在 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>
public Example()
{
InitializeComponent();
this.RootPanel.DataContext = this;
}
有很多关于如何将对象的数据上下文绑定到它自己的例子,例如
DataContext="{Binding RelativeSource={RelativeSource Self}}"
SomeOtherText="{Binding Text,RelativeSource={RelativeSource FindAncestor,AncestorType=UserControl}}"
但我找不到有关如何绑定到父级本身的答案。
解决方法
您可以使用相对源绑定绑定到父 UserControl
。
<Grid x:Name="RootPanel" DataContext="{Binding RelativeSource={RelativeSource FindAncestor,AncestorType={x:Type Example}}}">
relative source 将设置绑定到 Example
父控件的源。
默认情况下,绑定继承由 DataContext 属性指定的数据上下文(如果已设置)。但是,RelativeSource 属性是您可以显式设置 Binding 的源并覆盖继承的数据上下文的方法之一。
在这种情况下,Path
is empty 不会绑定到特定属性,而是绑定到控件本身。
要绑定到整个对象,您不需要指定 Path 属性。有关详细信息,请参阅 Data Binding Overview 中的“指定值的路径”。