【问题标题】:How to change the text of a textbox from a static method of another thread?如何从另一个线程的静态方法更改文本框的文本?
【发布时间】:2017-06-02 08:54:47
【问题描述】:

我在合并两个任务时遇到问题:Dispatcher.Invoke 并创建一个对象实例。

我有一个文本框:

<TextBox x:Name="txtuid">

这里是静态方法:

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

问题是,onCallback 正在另一个线程中运行,我必须将Dispatcher.Invoke 用于MainWindow my = new MainWindow(),但我该怎么做呢?

【问题讨论】:

  • 我从您的问题标题中删除了标签。请参阅here 为什么。
  • 感谢您的编辑。对不起!

标签: c# wpf multithreading static textbox


【解决方案1】:

您应该设置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;
}

【讨论】:

    【解决方案2】:

    在这种情况下,当您要实例化一个新的Control 而不是修改现有的Application.Current.Dispatcher 时,最简单的解决方案是使用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;
    }
    

    【讨论】:

    • 我没有收到任何错误,但文本没有改变。
    • 如果您从 UI 线程调用此方法而不使用调度程序,它是否有效?
    • 它也没有用。 mm8 向我展示了我的错误。非常感谢您对 Grx70 的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-12
    • 1970-01-01
    • 2010-11-11
    • 1970-01-01
    • 2023-03-30
    • 2012-12-21
    相关资源
    最近更新 更多