I have the following code in C# that I use to load a silverlight usercontrol dynamically. The usercontrol has some events that I would like to handle within my hosting application. The basics for the reflection should be the same for any C# application and I'm using .Net 3.5.
Here's my code: (It is raised after my WebClient downloads the DLL)
AssemblyPart
Assembly _mpc = ap.Load(e.Result);
MyControl = (UserControl)_mpc.CreateInstance("MyNamespace.MyControl");
MyControl.Width = 500;
MyControl.Height = 440;
CenterContent.Children.Add(MyControl);
Type t = MyControl.GetType();
EventInfo ei = t.GetEvent("MyEvent");
Type et = ei.EventHandlerType;
MethodInfo eventHandler = typeof(MainPage).GetMethod("OnMyEvent", BindingFlags.NonPublic);
Delegate d = Delegate.CreateDelegate(et, this, eventHandler.Name);
MethodInfo addHandler = ei.GetAddMethod();
Object[] addHandlerArgs = { d };
addHandler.Invoke(MyControl, addHandlerArgs);
// Initialize the User Control
MethodInfo mi = t.GetMethod("Init", new Type[]{typeof(string), typeof(int), typeof(string)});
mi.Invoke(MyControl, new object[] { App.Current.Host.Source.Host, App.Current.Host.Source.Port, strParam });
_mpc = null;
And here is the local event handler:
public
{
MessageBox
The problem I am facing is this:
I want to change the local event handler to private, but if I do (and change my BindingFlags to NonPublic) the debugger tells me that eventHandler is null (it's not finding the method) in this line:
It will call the OnMyEvent method if I add BindingFlags.Instance to BindingFlags.NonPublic; however, doing so makes it so that strValue is always null (even though it shouldn't be).
What am I doing wrong here?
Thanks,
Joshua Foulk