如何将面板的数据上下文绑定到 XAML 中的父对象?
How to bind a panel's data context to parent object in XAML?
在 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
父控件。
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.
在这种情况下,Path
is empty 不会绑定到特定的 属性,而是控件本身。
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.
在 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
父控件。
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.
在这种情况下,Path
is empty 不会绑定到特定的 属性,而是控件本身。
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.