绑定到 WPF 中的祖先 [英] Binding to an ancestor in WPF

查看:25
本文介绍了绑定到 WPF 中的祖先的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a window in one assembly that has a TextBlock control that I want to bind to the value of a Property of a class that is the property of the DataContext of that windows parent. The class that is serving as the DataContext is only defined within the second assembly. My question is what type do I need to specify as the Type in my binding statement. Can I just use the type of the DataContext's property that is common between the two assemblies or do I need to use the type of the DataContext?

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

The below is a prototype of how I think it should work but since it isn't I am confused about something :)

装配 #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());
     }
}

推荐答案

以下应该有效:

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

这篇关于绑定到 WPF 中的祖先的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆