wpf - 如何将面板的数据上下文绑定到 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}}}">
相对源将绑定源设置Example
为父控件。
默认情况下,绑定继承由 DataContext 属性指定的数据上下文(如果已设置)。但是,RelativeSource 属性是显式设置 Binding 的源并覆盖继承的数据上下文的方法之一。
在这种情况下Path
是空的,它不会绑定到特定的属性,而是控件本身。
要绑定到整个对象,您不需要指定 Path 属性。有关详细信息,请参阅数据绑定概述中的“指定值的路径” 。
推荐阅读
- sql - 在“WHERE”中的“CASE”语句中的“THEN”之后使用“Between”运算符
- python - Tensorflow:关于如何保存训练模型的差异
- c# - 试图了解 TFS 2017 标签变更集
- php - 访问其他网站时保持会话活跃
- python - Mac OS X 10.12.16 上的无头 selenium Firefox 是否可行?
- c++builder - 作为 POST 请求 (IdHTTP) 的结果下载文件
- angular - ngModel 绑定在 angular5 中没有按预期工作
- python - 将 Keras 模型集成到 TensorFlow 中
- sql - 将数据从几天聚合到一个月
- python - 将整个字典加载到特定的数据框单元格中