Social Icons

Change WPF window label content from another class and separate thread

From a different class;

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 works fine !
So next, I wanted to make this  from a different thread.
From a different thread;
Have you ever 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.
You can avoid this (if you are in the same window code behind) by,
Dispatcher.Invoke(new Action(() => { status_lable.Content = "Irantha signed in"; }));

From both different thread and another class;
So I needed to achieve both these situation together, I needed to access MainWindow.xaml label from a different class which is created on different thread rather than in main thread. I have done this and it works fine.

Enjoy! Don't forget to comment and like below ;)




6 comments:

  1. Thanks for the post. It helped me a great deal. I had to do little modification to work for me. If i dont mark it as background activity, until the thread is returned to original thread, it will not update. for example, in this case i had to update the text in background several times while i am making progress..

    ==== In the mainWindow.xaml.cs ======
    set { Dispatcher.Invoke(DispatcherPriority.Background, new Action(() => { status_lable.Content = value; })); }

    ==== from my SignIn.cs ======
    MainWindow.main.Status = "Irantha has signed in successfully-1";
    Thread.sleep(2000);

    MainWindow.main.Status = "Irantha has signed in successfully-2";
    Thread.sleep(2000);

    MainWindow.main.Status = "Irantha has signed in successfully-3";
    Thread.sleep(2000);

    MainWindow.main.Status = "Irantha has signed in successfully-4";
    Thread.sleep(2000);

    ReplyDelete
  2. This just literary saved my day.
    Thank you, thank you, and thank you!

    ReplyDelete
  3. It is fantastic: I even cannot understand Your code, however, it works for me fine. Thank you very much!!

    ReplyDelete
  4. Hey , if there is a continuous update from a different async thread then sometimes it is not working as expected , please suggest some other method

    ReplyDelete