从另一个类和单独的线程更改WPF主窗口标签 [英] Change WPF mainwindow label from another class and separate thread

查看:82
本文介绍了从另一个类和单独的线程更改WPF主窗口标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理WPF应用程序。我在 MainWindow.xaml 中有一个名为 Status_label的标签。我想从另一个类(signIn.cs)更改其内容。
通常我可以做到这一点

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";

但是我的问题是,当我试图通过signIn.cs类中的其他线程访问它时,则会出现错误:

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.

我可以使用 Dispatcher.Invoke(new Action(() => {.......... 还是其他?

编辑:
我将从不同的类以及单独的线程中调用该标签更改操作

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返回错误调用线程无法访问

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

请指导我,

谢谢

推荐答案

我解决了我的问题,希望有人会需要它。但是不知道这是否是优化的方法。

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

在我的 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; })); }
    }

来自我的 SignIn.cs

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

这对我来说很好。
您可以在这里找到更多详细信息,从另一个类和单独的线程更改WPF窗口标签内容

欢呼!!

这篇关于从另一个类和单独的线程更改WPF主窗口标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆