[英]adding winform user control event in c#
我現在正在學習 c#。
我在 vb 中設置了一個帶有 1 個按鈕(稱為 simpleButton1)的 winform 用戶控件(稱為 aUC),我可以執行以下操作。
dim aUC1 as aUC = new aUC()
'load user control to form
Me.controls.clear()
Me.controls.Add(aUC1)
' attach button event
AddHandler aUC1.simpleButton1.Click, AddressOf aUCButton_Click
所以我嘗試在 c# 上做同樣的事情
aUC aUC1 = new aUC();
' load user control to form
this.Controls.Clear();
this.Controls.Add(aUC1);
aUC1.simpleButton1.Click += aUCBtn_Click;
當我編譯我得到
aUC.simpleButton1 is inaccessible due to its protection level.
當我查看用戶控件上的設計器代碼時,我注意到
在VB它說
Friend WithEvents SimpleButton1 As DevExpress.XtraEditors.SimpleButton
在 c# 它說
private DevExpress.XtraEditors.SimpleButton simpleButton1;
當我在用戶控件設計生成的代碼上從私有更改為公共時,它可以正常工作。
我只是想知道 c# 中在主窗體上掛鈎用戶控件事件的標准做法是否是將控件從私有更改為公共; 或者對於 c# 有更好的方法/最佳實踐,我不想更改設計生成代碼上的代碼,以防我不小心把它填滿。
謝謝你。
問候
一旦您想從另一個 class 訪問按鈕,您應該將訪問修飾符從設計器更改為 public 沒有其他方法
但我會建議你學習 WPF 而不是 Winforms
正如凱厄斯所建議的那樣,
我在用戶控件上創建了一個按鈕單擊回調並將其公開事件
public partial class aUC : UserControl
{
public EventHandler aUCBtn_Click;
public aUC()
{
InitializeComponent();
}
private void simpleButton1_Click(object sender, EventArgs e)
{
if (aUCBtn_Click != null)
aUCBtn_Click(sender, e); // send event to public event
}
}
並在主要形式上消費該公共事件
public Form1()
{
InitializeComponent();
aUC aUC1 = new aUC();
this.Controls.Clear();
this.Controls.Add(aUC1);
aUC1.aUCBtn_Click += aUC1_Click; // hook to user control event
}
private void aUC1_Click(object sender, EventArgs e)
{
MessageBox.Show("btn click");
}
謝謝你。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.