【问题标题】:How to bind a panel's data context to parent object in XAML?如何将面板的数据上下文绑定到 XAML 中的父对象?
【发布时间】:2021-02-03 15:14:47
【问题描述】:

在 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}}"

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

【问题讨论】:

  • 结合"{Binding RelativeSource={RelativeSource Self}}""{Binding Text, RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}",你会得到"{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=UserControl}}"。在用户控件中更改 Datacontexts 是个坏主意
  • 感谢答案,不知何故,当我自己在发布问题之前检查它时,它似乎不起作用。至于警告,幸运的是,我对 WPF 仍然知之甚少,无法理解这种违规行为的影响:)

标签: wpf xaml data-binding panel datacontext


【解决方案1】:

您可以使用相对源绑定绑定到父 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 中的“指定值的路径”。

【讨论】:

    猜你喜欢
    • 2013-05-03
    • 2015-06-11
    • 2012-02-06
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 2013-05-04
    相关资源
    最近更新 更多