0

I am trying to remove a Delegate from an EventHandlerinXamarin.UWP. Specifically I am trying to implement a CustomRendererfor the Xamarin.FormsEntry, and I would like to remove an event handler delegate that has been assigned to the KeyUp EventHandlerforFormsTextBox` in Xamarin.

I have tried using the info found here, as well as here but it seems that does not work in Xamarin. Any thoughts on how I a can achieve this?

I have something like this in my OnElementChanged override for my CustomRenderer.

 FieldInfo f1 = typeof(Control).GetField("KeyUp",
   BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
            
object obj = f1.GetValue(this.Control);
            
PropertyInfo pi = this.Control.GetType().GetProperty("Events",  
  BindingFlags.NonPublic | BindingFlags.Instance);

EventHandlerList list = (EventHandlerList)pi.GetValue(this.Control, null);
list.RemoveHandler(obj, list[obj]);

the value of f1 always return null not sure what I'm doing wrong.

I also tried using the info from here to find the right event name (which I determined to be KeyUp), but it still doesn't work.

Kikanye
  • 1,198
  • 1
  • 14
  • 33
  • Null means that the control doesn't have a such field. Normally, get the keyup event with the code `EventInfo f1 = typeof(MainPage).GetEvent("KeyUp", BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);` – Liyun Zhang - MSFT Jun 28 '22 at 08:46

1 Answers1

0

Got it to work like this.

var keyUpRuntimeEvent = this.Control.GetType().GetRuntimeEvent("KeyUp");

Action<EventRegistrationToken> removeEventHandlerAction =
    (Action<EventRegistrationToken>)Delegate.CreateDelegate(typeof(Action<EventRegistrationToken>),
        this.Control,
        keyUpRuntimeEvent.RemoveMethod);

WindowsRuntimeMarshal.RemoveAllEventHandlers(removeEventHandlerAction);
this.Control.KeyUp += TextBoxOnKeyUp;

Kikanye
  • 1,198
  • 1
  • 14
  • 33