How to clone Control event handlers at run time?

廉价感情. 提交于 2019-12-18 13:14:42

问题


I want to duplicate a control like a Button, TextBox, etc. But I don't know how I can copy event handler methods (like Click) to the new control.

I have the following code now:

var btn2 = new Button();  
btn2.Text = btn1.Text;
btn2.size = btn1.size;
// ...
btn2.Click ??? btn1.Click

Is there any other way to duplicate a control?


回答1:


To clone all events of any WinForms control:

var eventsField = typeof(Component).GetField("events", BindingFlags.NonPublic | BindingFlags.Instance);
var eventHandlerList = eventsField.GetValue(button1);
eventsField.SetValue(button2, eventHandlerList);



回答2:


You just need to add the event handler method for the new button control. C# uses the += operator to do this. So you could simply write:

btn2.Click += btn1_Click

Alternatively, a somewhat more powerful approach is to use reflection. Of particular use here would be the EventInfo.AddEventHandler method.




回答3:


If you're simply looking to duplicate the HTML element that will eventually render (including attached event handlers), you can use below extension method to output a copy of the HTML.

/// <summary>
/// Render Control to HTML as string
/// </summary>
public static string Render(this System.Web.UI.Control control)
{
    var sb = new StringBuilder();
    System.IO.StringWriter stWriter = new System.IO.StringWriter(sb);
    System.Web.UI.HtmlTextWriter htmlWriter = new System.Web.UI.HtmlTextWriter(stWriter);
    control.RenderControl(htmlWriter);
    return sb.ToString();
}

Then you can use it to out put a copy in the aspx markup like this:

<%= btn1.Render() %>

If you want to modify, say, the text on the copy, you could do a string Replace on the Rendered html, or you could set the Text on the original button, and reset it after the Render call in the asx, i.e.:

<% btn1.Text = "Text for original button"; %>



回答4:


I didn't understand you question correctly. You can attach one event to multiple controls like this.

Button1.Click += button_click;
Button2.Click += button_click;



回答5:


the better approach is using a component class and inherit the control to that Class

public class DuplicateButton : OrginalButton
{

}

you can make changes in the partial class so there is no need for creating events



来源:https://stackoverflow.com/questions/6055038/how-to-clone-control-event-handlers-at-run-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!