簡體   English   中英

如何在C#Windows窗體中將Singleton userControl可見性設置為true或false?

[英]How to set Singleton userControl visibility to true or false in C# windows forms?

我已經實現了Singleton userControl ,以便在應用程序運行期間與其他類進行交互。 它在后台運行良好,但是我想在單擊button時顯示(設置可見性= true)設計的userControl 當Application運行時,我單擊button它在設計的表單中沒有顯示任何內容。 這是我在Form.cs文件中將可見性設置為true的Form.cs

private void ButtonSearch_Click(object sender, EventArgs e)
{
     panelYellow.Height = buttonSearch.Height;
     panelYellow.Top = buttonSearch.Top;
     searchPanel.getInstance().Visible = true;
}

這是我的單例userControl類定義的一部分:

public partial class searchPanel : UserControl
{
     private searchPanel()
     {
         InitializeComponent();

     }

     private static searchPanel sp = null;

     public static searchPanel getInstance()
     {
         if (sp == null)
         {
             sp = new searchPanel();
         }
         return sp;
     }
}

自從我沒有接觸過Winforms已經有一段時間了,但是從我的記憶中您不能真正為UserControl /表單添加私有構造函數。 但是另一可行的方法是,您可以嘗試通過使用Parent屬性設置它以其父窗體動態添加。 因為從我的角度來看,如果您不把它放在設計器中,它將永遠不會出現。

無論如何,問題將是:-為什么要為userControl使用單例?

您必須將searchPanel添加到窗體作為控件。

private void ButtonSearch_Click(object sender, EventArgs e)
{
     panelYellow.Height = buttonSearch.Height;
     panelYellow.Top = buttonSearch.Top;
     searchPanel.getInstance().Visible = true;
     this.Controls.Add(searchPanel.getInstance()); // add this line
}

同樣,您對Singleton的實現沒有錯,但可以改進。

public searchPanel()
{
    InitializeComponent();
    // write your Singleton code here
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM