vendredi 20 mars 2015

Unsubscribe another class from an event with Reflection

I'm working with a 3rd party library that is very tightly closed but doesn't do what I need it to (Xamarin.Forms, pan/zoom gestures).


I hacked up a work-around but with their latest update (1.4) the work-around stopped working. Looking at their code I can fix my work-around if I can unsubscribe one of the library's classes from listening to an event, the problem is that class has several private methods involved where they should have been protected.


Here's my code:



public class InteractiveEventTracker: EventTracker{
public InteractiveEventTracker(IVisualElementRenderer renderer)
: base(renderer)
{
this.Renderer = renderer;
var elChgMethod = typeof(EventTracker).GetMethod("OnElementChanged", BindingFlags.NonPublic | BindingFlags.Instance);
var elChgDelegate = Delegate.CreateDelegate(typeof(EventHandler<VisualElementChangedEventArgs>), elChgMethod);
// Compile-time errors, how do I spell that?
renderer.ElementChanged -= new EventHandler<VisualElementChangedEventArgs>(elChgDelegate);
}


The compile-time error is Expression denotes a 'variable' where a 'type' or 'method group' was expected.


My InteractiveEventTracker has to call the base constructor which looks like this:



public EventTracker(IVisualElementRenderer renderer)
{
if (renderer == null)
{
throw new ArgumentNullException("renderer");
}
this.renderer = renderer;
this.renderer.ElementChanged += new EventHandler<VisualElementChangedEventArgs>(this.OnElementChanged); // this is what I want to unsubscribe
}
private void OnElementChanged(object sender, VisualElementChangedEventArgs e){
...
}


How do I unsubscribe the base class, EventTracker, from listening to the event?






Aucun commentaire:

Enregistrer un commentaire