简体   繁体   English

如何从另一个线程的静态方法更改文本框的文本?

[英]How to change the text of a textbox from a static method of another thread?

I have got problems to combine two tasks: Dispatcher.Invoke and create an object instance. 我在组合两个任务时遇到问题: Dispatcher.Invoke并创建对象实例。

I have got a textbox: 我有一个文本框:

<TextBox x:Name="txtuid">

Here is the static method: 这是静态方法:

static private int onCallback(string Arr, int Len)
{
     MainWindow my = new MainWindow();
     my.txtuid.Text = Arr;
     ....
     return 0;
}

The problem is, that onCallback is running in another Thread and I have to use Dispatcher.Invoke for MainWindow my = new MainWindow() , but how can I do this? 问题是, onCallback在另一个线程中运行,我必须对MainWindow my = new MainWindow()使用Dispatcher.Invoke MainWindow my = new MainWindow() ,但是我该怎么做呢?

In this scenario when you're about to instantiate a new Control rather than modify already existing one the easiest solution is to use Application.Current.Dispatcher : 在这种情况下,当您要实例化一个新的Control而不是修改已经存在的Control ,最简单的解决方案是使用Application.Current.Dispatcher

static private int onCallback(string Arr, int Len)
{
    Application.Current.Dispatcher.Invoke(new Action(() =>
    {
        MainWindow my = new MainWindow();
        my.txtuid.Text = Arr;
        ....
    }));
    return 0;
}

You should to set the Text property of the existing instance of the MainWindow instead of creating a new one: 您应该设置MainWindow现有实例的Text属性,而不是创建一个新实例:

static private int onCallback(string Arr, int Len)
{
    Application.Current.Dispatcher.Invoke(new Action(() =>
    {
        MainWindow my = Application.Current.Windows.OfType<MainWindow>().FirstOrDefault();
        my.txtuid.Text = Arr;
    }));
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM