-->

这到底是什么WPF数据绑定的“的RelativeSource FindAncestor”吗?(Wha

2019-09-01 23:04发布

我目前一个WPF用户控件中工作(我的XAML文件的根元素是“用户控件”),我知道一个窗口内正在举行。 我如何使用数据绑定窗口的属性?

有谁知道为什么简单

<Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type Window}}" Path="..." />

不工作? 该错误消息我得到的是:

System.Windows.Data警告:4:不能用于与参考 '的RelativeSource FindAncestor,AncestorType =' 结合找到源System.Windows.Window 'AncestorLevel = '1''。

编辑:我结束了使用上ArsenMkrt的方式的变化,因此接受了他的答案。 然而,我在找出为什么FindAncestor不“只是工作”仍然有兴趣。

Answer 1:

最好的办法是给一个名称,用户控件

具有双向约束力创建用户控件依赖myProperty的属性,并将其绑定在主窗口中,比绑定在用户控件这样

<UserControl x:Name = "myControl">
     <Label Content={Binding ElementName= myControl, Path=MyProperty}/>
</UserControl>


Answer 2:

如果你想从“逃离” ItemsControlDataGridView得到一个Window ,你可以找到的是AncestorType x:Type Window不起作用。 或至少似乎并不...

如果这是你可能运行的混合或Visual Studio和期待的数据是在设计时看到的情况 - 它不会因为VS +混合既创造自己的情况下,这是不是真的窗口。 它会在运行时工作得很好,但不是在设计模式。

有几件事情可以做:

  • 裹在用户控件

  • 这里有一个替代的解决方案,我想出了。 它有一个优点,因为你没有引用一个UserControlWindow直接,因此,如果您更改父容器你的代码不会打破。

     <Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:views="clr-namespace:MyWPFApplication.Views" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="MyWPFApplication.Views.UPCLabelPrinterWindow" mc:Ignorable="d" x:Name="LayoutRoot" Title="UPCLabelPrinterWindow"> <views:DataContextWrapper> <DockPanel> ... </DockPanel> </views:DataContextWrapper> 

其中DataContextWrapper只是一个网格

namespace MyWPFApplication.Views {
   public class DataContextWrapper : Grid
   {

   }
}

然后当你绑定你这样做:

<TextBlock Text="{Binding="{Binding DataContext.SomeText, 
  RelativeSource={RelativeSource AncestorType={x:Type views:DataContextWrapper}, 
  Mode=FindAncestor}}" />

注意:如果你想绑定到窗口本身的属性很棘手,你应该通过一个依赖属性或类似的东西可能结合。 但是,如果你正在使用MVVM那么这是一个解决方案,我发现。



Answer 3:

我想你应该设置模式=“OneWayToSource”像这样:

<TextBox Text="{Binding RelativeSource={RelativeSource FindAncestor ,AncestorType={x:Type Grid}},Path=BackGround , Mode=OneWayToSource , UpdateSourceTrigger = PropertyChanged}" />


文章来源: What exactly does WPF Data Binding's “RelativeSource FindAncestor” do?