以上圖來說明,UserControl 內放置一個 Label 子控件,當滑鼠點擊觸發事件
- 綠色區域:UserControl.MouseClick
- 藍色區域:Label.MouseClick
該筆記是透過自訂 MouseClick 事件來達到點擊綠色、藍色區域都會觸發
UserControl 內自訂 CustomMouseClick 事件來整合要觸發的相關控件事件
using System.Windows.Forms;
namespace UCMouseClick
{
public partial class UserControl1 : UserControl
{
public event MouseEventHandler CustomMouseClick
{
add
{
MouseClick += value;
label1.MouseClick += value;
}
remove
{
MouseClick -= value;
label1.MouseClick -= value;
}
}
public UserControl1()
{
InitializeComponent();
}
}
}
Form 內註冊 UserControl.CustomeMouseClick 來觸發using System.Windows.Forms;
namespace UCMouseClick
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
userControl11.CustomMouseClick += UserControl11_CustomMouseClick;
}
private void UserControl11_CustomMouseClick(object sender, MouseEventArgs e)
{
MessageBox.Show("CustomMouseClick");
}
}
}
- 延伸閱讀
- [C#] Event 練習
- [C#] 自訂控制項內的事件 1、2
沒有留言:
張貼留言