[英]Call user written code/method from button click in usercontrol
我正在編寫一個用戶控件(winforms),該控件接受剪貼板中的圖像,進行一些操作,然后允許用戶上傳它並獲取圖像的URL。
我希望該控件的用戶編寫自己的代碼以上傳。 我在用戶控件中有一個上載按鈕,我想在單擊該按鈕時調用用戶編寫的代碼並傳遞圖像對象。
我嘗試使用委托,但使用委托,用戶必須調用它。 但是我希望用戶不應該調用它,而是應該在控件中單擊“上傳”按鈕時調用它。
我已閱讀以下內容,但沒有幫助
使用C#將方法傳遞為參數
如何將方法名稱傳遞給另一個方法並通過委托變量進行調用?
有什么方法可以允許用戶以使用控件的形式覆蓋上載方法,以便他可以編寫自己的代碼或其他內容? 有人可以指出我正確的方向嗎?
您可以通過兩種主要方法來實現此目的,一種方法是要求控件的用戶提供一個單擊“上載”按鈕時控件調用的上載方法,或者可以要求該控件是子類的,而上Upload
方法已實現。
方法1-提供在上載時要調用的委托:
public partial class MyControl
{
// Define a delegate that specifies the parameters that will be passed to the user-provided Upload method
public delegate void DoUploadDelegate(... parameters ...);
private readonly DoUploadDelegate _uploadDelegate;
public MyControl(DoUploadDelegate uploadDelegate)
{
if (uploadDelegate == null)
{
throw new ArgumentException("Upload delegate must not be null", "uploadDelegate");
}
_uploadDelegate = uploadDelegate;
InitializeComponent();
}
// ...
// Upload button Click event handler
public void UploadButtonClicked(object sender, EventArgs e)
{
// Call the user-provided upload handler delegate with the appropriate arguments
_uploadDelegate(...);
}
}
方法2-要求覆蓋上傳方法:
public abstract partial class MyControl
{
private readonly DoUploadDelegate _uploadDelegate;
protected MyControl()
{
InitializeComponent();
}
// ...
// The method that users of the control will need to implement
protected abstract void DoUpload(... parameters ...);
// Upload button Click event handler
public void UploadButtonClicked(object sender, EventArgs e)
{
// Call the overridden upload handler with the appropriate arguments
DoUpload(...);
}
}
對於后一種選擇,用戶需要先對控件進行子分類,然后才能使用它,如下所示:
public class MyConcreteControl : MyControl
{
protected override void DoUpload(... parameters ...)
{
// User implements their own upload logic here...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.