4

那里。我正在使用 C# .wpf,我从 C# 源代码中获得了一些代码,但我不能使用它。有什么我必须改变的吗?还是做?

 // Delegates to enable async calls for setting controls properties
    private delegate void SetTextCallback(System.Windows.Controls.TextBox control, string text);

    // Thread safe updating of control's text property
    private void SetText(System.Windows.Controls.TextBox control, string text)
    {
        if (control.InvokeRequired)
        {
            SetTextCallback d = new SetTextCallback(SetText);
            Invoke(d, new object[] { control, text });
        }
        else
        {
            control.Text = text;
        }
    }

如上代码,错误在InvokeRequiredInvoke

目的是,我有一个内容文本框,将为每个进程增加。

这是文本框的代码。SetText(currentIterationBox.Text = iteration.ToString());

代码有什么问题吗?

感谢您的任何帮助

编辑

// Delegates to enable async calls for setting controls properties
    private delegate void SetTextCallback(System.Windows.Controls.TextBox control, string text);

    // Thread safe updating of control's text property
    private void SetText(System.Windows.Controls.TextBox control, string text)
    {
        if (Dispatcher.CheckAccess())
        {
            control.Text = text;
        }
        else
        {
            SetTextCallback d = new SetTextCallback(SetText);
            Dispatcher.Invoke(d, new object[] { control, text });
        }
    }
4

3 回答 3

10

您可能从 Windows 窗体中获取了该代码,其中每个控件都有一个Invoke方法。在 WPF 中,您需要使用Dispatcher可通过Dispatcher属性访问的对象:

 if (control.Dispatcher.CheckAccess())
 {
     control.Text = text;
 }
 else
 {
     SetTextCallback d = new SetTextCallback(SetText);
     control.Dispatcher.Invoke(d, new object[] { control, text });
 }

此外,您没有SetText正确调用。它有两个参数,在 C# 中用逗号分隔,而不是等号:

SetText(currentIterationBox.Text, iteration.ToString());
于 2011-04-27T11:46:35.927 回答
6

在 WPF 中,您不使用 Control.Invoke 但 Dispatcher.Invoke 像这样:

Dispatcher.Invoke((Action)delegate(){
  // your code
});

采用

Dispatcher.CheckAccess()

首先检查。

于 2011-04-27T11:47:26.217 回答
3

在 WPF 中使用下一个构造:

if (control.Dispatcher.CheckAccess())
{
   ...
}
else
{
   control.Dispatcher.Invoke(...)
}
于 2011-04-27T11:48:24.877 回答