Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

I want to access my controls like button or textbox in mainWindow in WPF, but I can't do this.

In Windows Form application it's so easy, you can set modifier of that control to True and you can reach that control from an instance of that mainWindow, but in WPF I can't declare a public control. How can I do this?

like image 330
Ahad aghapour Avatar asked Nov 30 '12 11:11

Ahad aghapour


People also ask

How do I navigate between windows in WPF?

NavigationService is for browser navigation within WPF. What you are trying to do is change to a different window TrainingFrm . To go to a different window, you should do this: private void conditioningBtn_Click(object sender, RoutedEventArgs e) { var newForm = new TrainingFrm(); //create your new form.

How can I find WPF controls by name or type?

FindName method of FrameworkElement class is used to find elements or controls by their Name properties. This article shows how to find controls on a Window by name. FindName method of FrameworkElement class is used to find elements or controls by their Name properties.

How do I navigate from one page to another in WPF?

To package content for navigation, WPF provides the Page class. You can navigate from one Page to another declaratively, by using a Hyperlink, or programmatically, by using the NavigationService. WPF uses the journal to remember pages that have been navigated from and to navigate back to them.


1 Answers

To access controls in another WPF forms, you have to declare that control as public. The default declaration for controls in WPF is public, but you can specify it with this code:

<TextBox x:Name="textBox1" x:FieldModifier="public" /> 

And after that you can search in all active windows in the application to find windows that have control like this:

foreach (Window window in Application.Current.Windows) {     if (window.GetType() == typeof(Window1))     {        (window as Window1).textBox1.Text = "I changed it from another window";     } } 
like image 137
Ahad aghapour Avatar answered Sep 21 '22 18:09

Ahad aghapour