那里。 我正在使用 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;
}
}
如上代码,错误在InvokeRequired
和Invoke
目的是,我有一个包含内容的文本框,每个进程都会递增。
这是文本框的代码。 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 });
}
}
最佳答案
您可能从 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());
关于c# - C# .WPF 中的线程调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5803416/