简体   繁体   中英

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". I use pages "p1, p2, .." to replace "f". I want to access controls of "w" from "p1". How can I do that?

"w.xaml":

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

"p1.xaml":

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

"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. Another option is to add dependency properties for w's children you need to access in p1 and then bind them using relative binding. PS It'd be much easier to understand what you're after if you'd shown some code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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