2013-11-28 40 views
0

我創建了一個帶有加載PanelForm。這個想法是,我想顯示這個加載面板,直到我的動態創建的控件準備好顯示。防止Winforms控件在動態添加到控件集合時變爲可見

加載Panel最初是可見的,然後在OnShown事件期間,我創建我的控件並將其添加到頁面。我使用OnShown的原因是Form正在Mdi場景中使用,所以我需要它在我開始加載控件之前完全顯示(如果我在Load事件中嘗試這樣做,那麼Mdi Tab不會顯示,直到我的控制被加載)。

的問題是,有noticable忽悠我相信這是由於這樣的事實,當我加入我的控制到Controls集合:

一)Visible屬性立即設置爲true。 b)儘管z-index似乎是正確的,我的控件似乎出現在加載面板的前面。

這裏是問題

protected override void OnShown(EventArgs e) 
    { 
     Debug.WriteLine(loadingPanel.Visible); //true 
     Debug.WriteLine(Controls.GetChildIndex(loadingPanel)); //0 

     Debug.WriteLine(myControl.Visible); //false 

     myControl.Visible = false; 
     Controls.Add(myControl); 
     //** 

     Debug.WriteLine(myControl.Visible); //true 

     Debug.WriteLine(Controls.GetChildIndex(loadingPanel)); //0 
     Debug.WriteLine(Controls.GetChildIndex(myControl)); //1 

     Debug.WriteLine(loadingPanel.Visible); //true 

     base.OnShown(e); 
    } 

我希望我可以我的控件添加到集合,它會保持Visible = false這樣我就可以設置Visible = true當我控制的Load事件已完成的要點。相反,我的控制進入視野,我得到閃爍。有趣的是,如果我在任何時候都沒有設置loadingPanel.Visible = false,那麼一旦我的控件完成加載,loadPanel會重新出現並隱藏我的控件。

任何想法?

+0

您可以重寫paint方法並在OnShown方法中設置一個標誌,跳過任何繪畫操作直到添加完成。只是在黑暗中刺傷! – Charleh

+0

@Charleh能否再詳述一下,聽起來可能是值得嘗試的東西?也許在一個答案? – OffHeGoes

回答

0

有些奇怪的是,我這是怎麼設法解決我的問題:

protected override void OnShown(EventArgs e) 
{ 
    //trigger the OnLoad event of myControl - this does NOT cause it to appear 
    //over the loading Panel 
    myControl.Visible = true; 
    myControl.Visible = false; //set it back to hidden 

    //now add the control to the Controls collection - this now does NOT trigger the 
    //change to Visible, therefore leaving it hidden 
    Controls.Add(myControl); 

    //finally, set it to Visible to actually show it 
    myControl.Visible = true; 

    base.OnShown(e); 
} 

我只能假設,添加控件時控件集合,然後如果沒有創建的句柄會自動將其設置爲可見。通過在將其添加到集合之前使其可見,相關的句柄由創建而不影響父控件。然後,當它稍後添加到集合中時,它仍然不會影響父控件。

0

我認爲你的mycontrol是一個標準的winforms控件?爲什麼不創建一個自定義控件,其中包含所需的mycontrol,並且在該自定義控件中,默認將「子」控件的可見屬性設置爲false?

還沒有測試過這個,但那就是我接下來會做什麼...?

+0

對不起,我應該說我的控件是一個自定義的UserControl。我相信你的建議不會改變任何東西,因爲Controls.Add就是將控件上的Visible屬性設置爲true。 – OffHeGoes

+0

是的,但默認你的「孩子」控件可見= false?在加載之前不要「設置」它爲可見= false,默認情況下讓子控件爲可見= false?然後將它們設置爲visible = true? –

0

即使您成功將其設置爲false,您不需要更改Visible,但是當您將它們顯示出來時,如果控件數量很大,仍然會出現閃爍現象。你應該重寫OnLoad方法,並使用SuspendLayoutResumeLayout這樣的:

//Start adding controls 
SuspendLayout(); 
//.... 

//in the OnLoad 
protected override void OnLoad(EventArgs e){ 
    ResumeLayout(true); 
} 

我懷疑使用ResumeLayout(true)右後整理添加控件可能是OK,你也應該嘗試。