2017-05-26 55 views
1

我已經創建了一個包含按鈕的用戶控件。我們的目標是爲我的按鈕,將通過應用程序重複使用創建自定義佈局:鼠標單擊事件不fireing

public partial class Button : UserControl 
{ 
    public Button() 
    { 
     InitializeComponent(); 
     button1.BackColor = Color.FromArgb(0, 135, 190); 
     button1.ForeColor = Color.Black; 
    } 

    [Description("Test text displayed in the textbox"), Category("Data")] 
    public string TextSet 
    { 
     set { button1.Text = value; } 
     get { return button1.Text; } 
    } 
} 

當我添加一個按鈕,用戶控制我的應用程序,併爲鼠標點擊事件,該事件不火。 (顯然,按鈕的每個實例將有鼠標點擊不同的事件)

我必須做一些事情在我的按鈕用戶控制碼轉發鼠標點擊事件?

+0

什麼是Button1的?什麼是您設置事件處理程序的確切代碼? –

+0

從我看到的按鈕(繼承)用戶控件,但你說的用戶控件有(組成)按鈕的代碼?另外你在哪裏試圖處理內部用戶控件或窗體託管用戶控件內的單擊事件? –

回答

2

您訂閱的用戶控件的點擊。但是您要點擊位於用戶控件上的按鈕。因此用戶控制的點擊事件不會被觸發。您可以手動提升用戶控件的Click事件時,點擊button1

public partial class Button : UserControl 
{ 
    public Button() 
    { 
     // note that you can use designer to set button1 look and subscribe to events 
     InitializeComponent(); 
     button1.BackColor = Color.FromArgb(0, 135, 190); 
     button1.ForeColor = Color.Black; 
    } 

    // don't forget to subscribe button event to this handler 
    private void button1_MouseClick(object sender, MouseEventArgs e) 
    { 
     OnMouseClick(e); // raise control's event 
    } 

    // ... 
} 

但最好還是從Button類直接繼承您的按鈕:

public partial class CustomButton : Button 
{ 
    public CustomButton() 
    { 
     BackColor = Color.FromArgb(0, 135, 190); 
     ForeColor = Color.Black; 
    } 

    [Description("Test text displayed in the textbox"), Category("Data")] 
    public string TextSet 
    { 
     set { Text = value; } 
     get { return Text; } 
    } 
} 
+0

我得到這個錯誤: 錯誤\t CS0060 \t不一致的可訪問性:基類'Button'不如類'CustomButton'可訪問 –

+0

@ Q-bertsuit請確保您從* System.Windows.Forms.Button *繼承你的*按鍵*類的 –

+1

謝謝!有效! –