Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

c# - Binding to an ancestor in WPF

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 :)

Assembly #1
Window

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

Assembly #2
Application Shell

class Shell 
{
     public Client Client { get { return client; } set { client = value; } }
     OnStartup()
     {
          NavigationWindow window = new NavigationWindow();
          window.DataContext = this;
          window.Navigate(GetHomeView());
     }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

the following should work :

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...