首页 > 解决方案 > 如何将面板的数据上下文绑定到 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}}"

但我找不到关于如何绑定到父级本身的答案。

标签: wpfxamldata-bindingpaneldatacontext

解决方案


UserControl您可以使用相对源绑定绑定到父级。

<Grid x:Name="RootPanel" DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Example}}}">

相对源将绑定源设置Example为父控件。

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

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

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


推荐阅读