swapnil saha
swapnil saha

Reputation: 1320

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
}

Upvotes: 6

Views: 7405

Answers (2)

KANAX
KANAX

Reputation: 285

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";
}

Upvotes: 11

Alex Seleznyov
Alex Seleznyov

Reputation: 945

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. P.S. It'd be much easier to understand what you're after if you'd shown some code.

Upvotes: 0

Related Questions