如何将面板的数据上下文绑定到 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 父控件的源。

默认情况下,绑定继承由 DataContext 属性指定的数据上下文(如果已设置)。但是,RelativeSource 属性是您可以显式设置 Binding 的源并覆盖继承的数据上下文的方法之一。

在这种情况下,Path is empty 不会绑定到特定属性,而是绑定到控件本身。

要绑定到整个对象,您不需要指定 Path 属性。有关详细信息,请参阅 Data Binding Overview 中的“指定值的路径”。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...