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
}
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.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With