I appreciate any help with this.
Scenario:
A winforms application that creates a form from WPF Xaml. Catch is that we
cannot use Framework 3.0, must use 2.0. This is not a problem. I just parse
the Xaml as Xml and construct the winforms controls with
Activator.CreateInstance. The problem comes in the events. Our client wants
to allow their clients to specify custom eventhandlers and to provide them in
a custom assembly.
My Code:
temp - the control that fires the event
einfo - the EventInfo for the event
val - the name of the method to be used as eventhandler for the event
private void ControlSetEventHandler(Control temp, EventInfo einfo, string val)
{
Assembly assem = Assembly.Load("ThirdParty.Finance.Assembly");
Type tExForm = assem.GetType("Client.Xforms.XamlGenerator.EventHandlers");
// Get the type of delegate that handles the event.
Type tDelegate = einfo.EventHandlerType;
// If you already have a method with the correct signature,
// you can simply get a MethodInfo for it.
MethodInfo miHandler = tExForm.GetMethod(val, BindingFlags.Public |
BindingFlags.Instance);
// Create an instance of the delegate. Using the overloads
// of CreateDelegate that take MethodInfo is recommended.
Delegate d = Delegate.CreateDelegate(tDelegate, temp, miHandler);
// Get the "add" accessor of the event and invoke it late-
// bound, passing in the delegate instance. This is equivalent
// to using the += operator in C#, or AddHandler in Visual
// Basic. The instance on which the "add" accessor is invoked
// is the form; the arguments must be passed as an array.
MethodInfo addHandler = einfo.GetAddMethod();
Object[] addHandlerArgs = { d };
addHandler.Invoke(temp, addHandlerArgs);
}
The Error:
"Error binding to target method"
occurs at line: Delegate d = Delegate.CreateDelegate(tDelegate, temp,
miHandler);
The 3rd party assembly is not referenced by the form project and is located
in the bin/debug folder (I have tried it with the 3rd party assembly added as
a reference). The target method has a signature: public void
MethodName(object sender, EventArgs e). einfo is a Click event. temp is a
button.
This problem only occurs when I get the method from the 3rd party assembly.
If I move the method into the form where ControlSetEventHandler is located
and adjust it to get the event from the Assembly.GetExecutingAssembly it
works fine. That, of course does not meet the clients needs.
|