Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change WPF mainwindow label from another class and separate thread

Im working on a WPF application. I have a label called "Status_label" in MainWindow.xaml. and I want to change its content from a different class (signIn.cs). Normally I'm able to do this

var mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
mainWin.status_lable.Content = "Irantha signed in";

But my problem is,when I'm trying to access it via different thread in signIn.cs class, it gives an error:

The calling thread cannot access this object because a different thread owns it.

Can I solve this by using Dispatcher.Invoke(new Action(() =>{.......... or something else?

EDIT: I'm gonna call this label change action from different class as-well-as separate thread

MainWindow.xaml

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

SignIn.cs

    internal void getStudentAttendence()
    {
        Thread captureFingerPrints = new Thread(startCapturing);
        captureFingerPrints.Start();
    }

void mySeparateThreadMethod()
{
    var mainWin = Application.Current.Windows.Cast<Window>().FirstOrDefault(window => window is MainWindow) as MainWindow;
    mainWin.status_lable.Dispatcher.Invoke(new Action(()=> mainWin.status_lable.Content ="Irantha signed in"));
}

line var mainWin return errorThe calling thread cannot access this object because a different thread owns it.

Please guide me,

Thank you

like image 334
iJay Avatar asked Mar 15 '13 05:03

iJay


2 Answers

I resolved my question, hope somebody will need this. But don't know whether this is the optimized way.

In my mainWindow.xaml.cs :

    public  MainWindow()
    {
      main = this;
    }

    internal static MainWindow main;
    internal string Status
    {
        get { return status_lable.Content.ToString(); }
        set { Dispatcher.Invoke(new Action(() => { status_lable.Content = value; })); }
    }

from my SignIn.cs class

 MainWindow.main.Status = "Irantha has signed in successfully";

This works fine for me. You can find more details from here, Change WPF window label content from another class and separate thread

cheers!!

like image 98
iJay Avatar answered Oct 07 '22 11:10

iJay


try below snippet:

status_lable.Dispatcher.Invoke(...)
like image 37
David Avatar answered Oct 07 '22 11:10

David