Irantha Jayasekara
Irantha Jayasekara
Digital Products & Solution Provider

Drink A Coffee With Me Today

Loading...
Success!
Error!

Follow Me On Instagram

alt text alt text alt text alt text alt text alt text
Available For Freelance
Menu
Close
December 02, 2014

Change WPF window label content from another class and a separate thread

By Irantha
C# Programming

Once I was working on a WPF application, I had a label called "Status_label" in MainWindow.xaml. I wanted to change its content from a different class (signIn.cs).


MainWindow.xaml
<Label HorizontalAlignment="Left" Margin="14,312,0,0" Name="status_lable" Width="361"/>

To change MainWindow.xaml label content from different class:
var mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
mainWin.status_lable.Content = "Irantha signed in";

It worked fine !

So next, I wanted to make this from a different thread:
Then I experienced this;
"The calling thread cannot access this object because a different thread owns it."
Whenever you update your UI elements from a thread other than the main thread, you will see this error. I overcome this issue by,

Dispatcher.Invoke(new Action(() => { status_lable.Content = "Irantha signed in"; }));
Successful!

From both different thread and another class;
The situation was changed and I needed to achieve both above scenarios together, I needed to access MainWindow.xaml label from a different class which is created on different thread rather than in main thread. I came a cross the following solution.


Hope this helps you. Please comment your thoughts. If you have a problem ask here, I'll try my best to help you. Or we can discuss each other.
Cheers!
Author Details
Irantha Jayasekara
Irantha Jayasekara

Software Developer, Web Developer, Freelancer, Project Manager & Google Apps Scripts and API expert

Share Post