1
我試過沒有成功,請遵循此處和其他論壇上給出的代碼。我無法讓事件發生。對由動態控件引發的事件的後期綁定 - 事件不會觸發
手動添加到表單的相同控件工作正常......它引發了事件並且父表單消耗它。所以控制能夠工作,而不是以我現在(到目前爲止)試圖用Reflection完成的方式。
我可以從這裏下載的Web應用程序的一個小DEMO:
http://ube.dev.campuswebstore.mobi/dloadfile.htm
下面是代碼,我會評論我在哪裏試圖將事件鏈接到處理程序(的一部分不工作):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Reflection;
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Init(object sender, System.EventArgs e)
{
TestRaiseEvent77.ButtonClickEvent += new ButtonWasClicked(TestRaiseEvent77_ButtonClickEvent);
string layout = "";
if (Request.QueryString["layout"] != null)
{
layout = Request.QueryString["layout"] as string;
}
else
{
layout = "default";
}
if (!Page.IsPostBack)
{
GlobalMethods.InitControlList();
LoadControls(layout);
AddControlsFromList();
WireControlEventsToHandlers();
}
else
{
AddControlsFromList();
WireControlEventsToHandlers();
}
}
void TestRaiseEvent77_ButtonClickEvent(string message)
{
}
private void AddControlsFromList()
{
sitemanagercontrolsdiv.Controls.Clear();
try
{
if (GlobalMethods.divlayoutgencontrols != null)
{
foreach (Control c in GlobalMethods.divlayoutgencontrols)
{
sitemanagercontrolsdiv.Controls.Add(c);
}
}
}
catch (Exception eee)
{
string a = eee.Message;
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
//注:
//The control collection cannot be modified during
//DataBind,
//Init,
//Load,
//PreRender or
//Unload phases.
private void WireControlEventsToHandlers()
{
foreach (Control c in sitemanagercontrolsdiv.Controls)
{
Type controlType = c.GetType();
BindingFlags myBindingFlags = BindingFlags.Instance | BindingFlags.Public;
EventInfo[] myEvents = controlType.GetEvents(myBindingFlags);
for (int j = 0; j < myEvents.Count(); j++)
{
string eventName = myEvents.ElementAt(j).Name;
if (eventName == "ButtonClickedEvent")
{
MethodInfo handler = typeof(_Default).GetMethod("SomeHandler");
Delegate del = Delegate.CreateDelegate(myEvents.ElementAt(j).EventHandlerType, this, handler);
////////////////////////////////無論這是做什麼工作不
myEvents.ElementAt(j).AddEventHandler(c, del);
}
}
c.Visible = true;
string tempGUID = Guid.NewGuid().ToString();
c.ID = "TestRaiseEvent" + tempGUID + "1";
}
}
private void LoadControls(string layout)
{
Control c = LoadControl("~/TestRaiseEvent.ascx");
GlobalMethods.divlayoutgencontrols.Add(c);
}
//////////////////我試圖聯絡的事件給這個處理程序:
public void SomeHandler(string message)
{
// do something
}
}
}
請隨時紀念這個作爲回答。 –