0

I created a keypad that has increment and decrement buttons for a touch screen interface. I also overrode TextBox to create a control that will increase or decrease the current integer by 1 when the keypad buttons are pressed. My constructor is registering for the DecrementClickedEvent like this:

EventManager.RegisterClassHandler(
            typeof(UIElement), SoftKeyPad.DecrementClickedEvent,
            (RoutedEventHandler)OnDecrement);

and here is my handler:

private void OnDecrement(object sender, RoutedEventArgs e)
      {
         try
         {
            if (this.IsFocused)
            {
               var currentNumber = Convert.ToInt32(Text) - 1;
               Text = currentNumber.ToString();
            }
         }
         catch (Exception)
         {
            //If we can't convert, we can't decrement.
            if (Text.IsNullOrEmpty())
            {
               Text = "0";
            }
         }
      }

This however leads to memory leaks I've discovered because the handlers need to be static. If I make the handlers static though, I can't get the text in order to change it. Am I going about this the wrong way? If I make OnDecrement static, how can I edit the text?

  • Maybe the [WeakEventListener](https://learn.microsoft.com/en-us/dotnet/framework/wpf/advanced/weak-event-patterns) will help you out: read up in https://stackoverflow.com/questions/3662842/how-do-events-cause-memory-leaks-in-c-sharp-and-how-do-weak-references-help-miti - there is a John Skeet article listet there that might help you out. I am not quite getting why you need to make something static though - maybe elaborate? http://csharpindepth.com/Articles/Chapter2/Events.aspx (article) – Patrick Artner Dec 09 '17 at 16:46
  • 2
    Use the *sender* argument to get a reference to the control. – Hans Passant Dec 09 '17 at 16:52
  • The sender is the keypad though, not the TextBox. – Brett Atkinson Dec 09 '17 at 17:11

0 Answers0