How to access WPF MainWindow controls from another window ?

Updated on     Kisan Patel

Problem:

How to access WPF MainWindow controls from another window?
How to access one window’s control (richtextbox) from another window in wpf?

Solution:

Application.Current contains a collection of all windows in you application, you can get the other window with a query such as

var window2 = Application.Current.Windows
 .Cast<Window>()
 .FirstOrDefault(window => window is Window2) as Window2;

and then you can reference the control from your code, as in

var richText = window2.MyRichTextBox;

For Example, if you want to access WPF MainWindow then use below code:

((MainWindow)System.Windows.Application.Current.MainWindow).TextBlock1.Text = "Setting Text from My Program";

WPF

Leave a Reply