如何将WPF Dispatcher转换为WinForms

7

我正在将一个方法从WPF项目移植到WinForms项目中。

除了这一部分之外,其他都被顺利移动:

private void ServerProcErrorDataReceived(object sender, DataReceivedEventArgs e)
{
  // You have to do this through the Dispatcher because this method is called by a different Thread
  Dispatcher.Invoke(new Action(() =>
  {
    richTextBox_Console.Text += e.Data + Environment.NewLine;
    richTextBox_Console.SelectionStart = richTextBox_Console.Text.Length;
    richTextBox_Console.ScrollToCaret();
    ParseServerInput(e.Data);
  }));
}

我不知道如何将Dispatcher转换为winforms。

有人能帮忙吗?


如果你的WPF代码可以很好地转换为winforms,那么很可能你做错了。与WPF相比,winforms的数据绑定能力非常有限。 - Federico Berasategui
4
有时候,你没有选择使用哪种技术。 - Shimrod
@HighCore,C#代码转移过来很顺利...不确定问题出在哪里? - ErocM
2
@HighCore:好的,但这与什么有关?他必须进行翻译。你的观点是什么?将WPF转换为WinForms并不需要一些杰出的技术洞见。 - Ed S.
我并不是有意冒犯你,"winforms的数据绑定能力与WPF相比确实非常有限"这句话听起来有些教条主义。但现在我理解了你的观点。 - Shimrod
显示剩余2条评论
1个回答

13

您应该使用Invoke来替换Dispatcher

private void ServerProcErrorDataReceived(object sender, DataReceivedEventArgs e)
{
    if (richTextBox_Console.InvokeRequired)
    {
        richTextBox_Console.Invoke((MethodInvoker)delegate
        {
            ServerProcErrorDataReceived(sender, e);
        });
    }
    else
    {
        richTextBox_Console.Text += e.Data + Environment.NewLine;
        richTextBox_Console.SelectionStart = richTextBox_Console.Text.Length;
        richTextBox_Console.ScrollToCaret();
        ParseServerInput(e.Data);
    }
}

1
更具体地说,使用 richTextBox_Console 上的 Invoke 方法。 - Brian Ball

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接