Change WPF mainwindow label from another class and separate thread

iJay picture iJay · Mar 15, 2013 · Viewed 16.2k times · Source

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

Answer

iJay picture iJay · Mar 28, 2013

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!!