Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 624
swapnil saha Avatar asked Jul 20 '16 07:07

swapnil saha


People also ask

How can I access a control in WPF from another class or window?

If you want to access a control on a wpf form from another assembly you have to use the modifier attribute x:FieldModifier="public" or use the method proposed by Jean. Save this answer.

How do I display a WPF window?

When a Window is created at run-time using the Window object, it is not visible by default. To make it visible, we can use Show or ShowDialog method. Show method of Window class is responsible for displaying a window.

What is Page window in WPF?

Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications.


1 Answers

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";
}
like image 99
KANAX Avatar answered Sep 27 '22 16:09

KANAX