【发布时间】: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