简体   繁体   English

如何从WPF中的子页面访问父窗口的控件?

[英]How can I access control of parent window from child page in WPF?

I have a window "w" with several controls and a frame "f". 我有一个窗口“w”,有几个控件和一个框架“f”。 I use pages "p1, p2, .." to replace "f". 我使用页面“p1,p2,..”来代替“f”。 I want to access controls of "w" from "p1". 我想从“p1”访问“w”的控件。 How can I do that? 我怎样才能做到这一点?

"w.xaml": “w.xaml”:

<Window x:Class="WpfApplication.w">
    <Grid>
        <TextBox x:Name="textBox_1" />
        <Frame x:Name="mainFrame" />
    </Grid>
</window>

"p1.xaml": “p1.xaml”:

<Page x:Class="WpfApplication.p1">
    <Grid>
        <Button x:Name="button_1"
            Click="Button_Click" />
    </Grid>

"p1.xaml.cs": “p1.xaml.cs”:

private void Button_Click_Upload(object sender, RoutedEventArgs e)
{
    //set text of textBox_1
}

You can do 你可以做

private void Button_Click_Upload(object sender, RoutedEventArgs e)
{
    ((w)App.Current.MainWindow).textBox_1.Text = "Your Text";
    //or 
    ((w)Window.GetWindow(this)).textBox_1.Text = "Your Text";
}

If you're not against tight coupling, just link "w" with "p1" by means of a property or constructor parameter.You might want to add an interface 'Iw' to loose your coupling a bit. 如果你不反对紧耦合,只需通过属性或构造函数参数链接“w”和“p1”。你可能想要添加一个接口'Iw'来松散你的耦合。 Another option is to add dependency properties for w's children you need to access in p1 and then bind them using relative binding. 另一个选择是为你需要在p1中访问的w子项添加依赖项属性,然后使用相对绑定绑定它们。 PS It'd be much easier to understand what you're after if you'd shown some code. PS如果您显示了一些代码,那么理解您所追求的内容要容易得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM