调用UserControl不起作用

时间:2015-06-08 06:16:42

标签: c# multithreading winforms

我有一个表单(MainPage)并且我在其中设置了一个UserControl,所以我按照这样的形式编写一个方法来调用:

delegate void containerPanelCallback(UIPart uiPart);
public void IncludeUIPart(UIPart uiPart)
{
    if (this.containerPanel.InvokeRequired)
    {
        containerPanelCallback d = new containerPanelCallback(IncludeUIPart);
        containerPanel.Invoke(d, new object[] { uiPart });
    }
    else
    {
        containerPanel.Controls.Clear();
        containerPanel.Controls.Add(uiPart);
    }
    uiPart.Size = this.containerPanel.Size;
    uiPart.Dock = DockStyle.Fill;
}

UIPart类继承自UserControl我的UserControls继承自UIPart

此方法和调用启动如下:

public class myClass
{ 
...
private static MainPage _frmMain;
private static myUIPart6 UIP6;
...
public static void aMethod(/* Some arguments */)
{
    UIP6 = new myUIPart6 { /* Some settings of properties */ };
    _frmMain.IncludeUIPart(UIP6);
    _frmMain.Show(); /*Throws an error*/
}
...
}

错误是:

  

跨线程操作无效:控制' MainPage'从创建它的线程以外的线程访问。

我在这里找到了很多关于这个错误的问题和许多答案,但是我无法弄清楚为什么它会在_frmMain.Show();投掷?,我应该调用别的吗?还是我错了?它与我的UserControl的Handle的创建有关吗?

2 个答案:

答案 0 :(得分:2)

尝试添加以下代码:

class Foo 
{
    static Form _frmMain;
    public static void aMethod()
    {
        _frmMain.Show(); 
    }        
    public static void aMethodCaller()
    {
        if (_frmMain.InvokeRequired)
            _frmMain.Invoke(new Action(aMethod));
        else
            aMethod();
    }
}

并将代码中对aMethod()的所有引用替换为aMethodCaller()

以下是示例代码:

string test = "This is test string";
string::size_type position;
position = test.find(ID);
if (position != test.npos){
    cout << "Found: " << position << endl;
}
else{
    cout << "not found ID << endl;
}

答案 1 :(得分:1)

_frmMain.Show()没有受到任何调用要求检查的保护。所以你可能在后台线程中调用它。

相关问题