簡體   English   中英

WPF 數據綁定的“RelativeSource FindAncestor”究竟是做什么的?

[英]What exactly does WPF Data Binding's “RelativeSource FindAncestor” do?

我目前正在使用 WPF 用戶控件(我的 XAML 文件的根元素是“UserControl”),我知道它被托管在一個 Window 中。 如何使用數據綁定訪問 Window 的屬性?

有誰知道為什么簡單

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

不起作用? 我得到的錯誤信息是:

System.Windows.Data 警告:4:無法找到引用“RelativeSource FindAncestor, AncestorType='System.Windows.Window', AncestorLevel='1''的綁定源。

編輯:我最終使用了 ArsenMkrt 方法的變體,因此接受了他的回答。 但是,我仍然有興趣找出 FindAncestor 不“正常工作”的原因。

最好的方法是給 UserControl 起一個名字

使用兩種方式綁定在 UserControl 中創建依賴屬性 MyProperty 並將其綁定在主窗口中,而不是像這樣在 UserControl 中綁定

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

如果您嘗試從ItemsControlDataGridView '轉義'以到達Window您可能會發現x:Type Window AncestorType 不起作用。 或者至少似乎沒有……

如果是這種情況,您可能正在運行 Blend 或 Visual Studio 並希望數據在設計時可見 - 這不會,因為 VS + Blend 都創建了自己的實例,但它們並不是真正的 Windows。 它可以在運行時正常工作,但不能在設計模式下工作。

您可以做以下幾件事:

  • 包裝在用戶控件中

  • 這是我想出的替代解決方案。 它的一個優點是您不直接引用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}}" />

注意:如果你想綁定到一個屬性 ON Window 本身就比較棘手,你可能應該通過依賴屬性或類似的東西進行綁定。 但是,如果您使用的是 MVVM,那么這是我找到的一種解決方案。

我認為你應該 SET Mode="OneWayToSource" 像這樣:

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

如果您使用視圖模型作為 Window 的 DataContext 並且您需要綁定到的屬性來自該視圖模型,那么您應該使用 DataContext.MyPropertyPath 作為路徑前綴,如下所示:

<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType={x:Type Window}, Mode=FindAncestor}}"/>

這翻譯為“為我找到一個祖先窗口,然后在它的數據上下文中查找 MyProperty”

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM