【问题标题】:Binding to an ancestor in WPF绑定到 WPF 中的祖先
【发布时间】:2011-03-25 06:50:54
【问题描述】:

我在一个程序集中有一个窗口,它有一个 TextBlock 控件,我想将它绑定到一个类的属性值,该类是该窗口父级的 DataContext 的属性。用作 DataContext 的类仅在第二个程序集中定义。我的问题是我需要在绑定语句中指定什么类型作为类型。我可以只使用两个程序集之间通用的 DataContext 属性的类型,还是需要使用 DataContext 的类型?

下面是我认为它应该如何工作的原型,但因为它不是我对某些事情感到困惑:)

大会 #1
窗口

<TextBlock 
    Text="{Binding RelativeSource={RelativeSource 
        AncestorType={x:Type client:Client}}, Path=Name }"/>

大会 #2
应用程序外壳

class Shell 
{
     public Client Client { get { return client; } set { client = value; } }
     OnStartup()
     {
          NavigationWindow window = new NavigationWindow();
          window.DataContext = this;
          window.Navigate(GetHomeView());
     }
}

【问题讨论】:

    标签: c# wpf data-binding


    【解决方案1】:

    以下应该有效:

    <TextBlock Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,
                                                             AncestorType={x:Type Window}},
                                                             Path=DataContext.Client.Name}" />
    

    【讨论】:

    • 完美。直接绑定到 Entity Framework Core 模型对象(在 ViewModel 内)时也能正常工作,但组合框的内容(ViewModel 内的单独列表)除外。
    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 2019-06-09
    • 2011-10-13
    • 2015-04-14
    • 2011-01-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    相关资源
    最近更新 更多