InvokeRequired和ToolStripStatusLabel

时间:2012-09-14 06:30:58

标签: c# winforms .net-3.5 invokerequired

在我的应用程序中,我有一个负责所有数据库操作的类。它从主类调用,并在动作完成后使用委托调用方法。 因为它是异步的,所以我必须在我的GUI上使用invoke,所以我创建了一个简单的扩展方法:

 public static void InvokeIfRequired<T>(this T c, Action<T> action)
            where T: Control
        {
            if (c.InvokeRequired)
            {
                c.Invoke(new Action(() => action(c)));
            }
            else
            {
                action(c);
            }
        }

当我尝试在textBox上调用它时,这工作正常:

textBox1.InvokeIfRequired(c => { c.Text = "it works!"; });

但是当我尝试在ToolStripStatusLabel或ToolStripProgressBar上调用它时出现错误:

  

'System.Windows.Forms.ToolStripStatusLabel'类型不能用作   在泛型类型或方法中输入参数“T”   'SimpleApp.Helpers.InvokeIfRequired(T,System.Action)'。有   没有隐式引用转换   'System.Windows.Forms.ToolStripStatusLabel'来   'System.Windows.Forms.Control的'。

我知道这可能是一个简单的修复,但我只能处理它:/

3 个答案:

答案 0 :(得分:8)

这是因为ToolStripItem(导致错误的两个基础)是Component而不是Control。 尝试在拥有它们的工具条上调用您的扩展方法并调整您的委托 方法

答案 1 :(得分:0)

我想总结一下已接受的解决方案。您可以使用ToolStripStatusLabel的GetCurrentParent方法从组件中获取控件。

执行toolStripStatusLabel1.InvokeIfRequired代替toolStripStatusLabel1.GetCurrentParent().InvokeIfRequired

答案 2 :(得分:0)

使用 GetCurrentParent().InvokeRequired

的扩展方法
public static void ToolStripStatusInvokeAction<TControlType>(this TControlType control, Action<TControlType> del)
    where TControlType : ToolStripStatusLabel
    {
        if (control.GetCurrentParent().InvokeRequired)
            control.GetCurrentParent().Invoke(new Action(() => del(control)));
        else
            del(control);
    }

调用ToolStripStatusInvokeAction扩展程序:

toolStripAppStatus.ToolStripStatusInvokeAction(t =>
{ 
    t.Text= "it works!";
    t.ForeColor = Color.Red;
});
相关问题