简体   繁体   中英

SizeChanged event being fired recursively

I have a SizeChanged event in one of my windows. One of the user controls Width's is behaving interestingly, so I decided to staticly set the width of my window in a SizeChanged event. Problem is, when I set the size of the window in the size changed event, it fires another size changed event! I want the user to be able to resize the window, and then only have the event fire once. I have tried :

e.Handled = true;

As well as adding an event handler in the window constructor, and removing it in the size changed event. (This makes it only be able to fire once and won't ever fire again in the window's lifetime). Any ideas?

you should use a private bool and change its value when the size changed

bool _sizeChanged=false;
void handleResize(Object sender, EventArgs e)
{
  if (_sizeChanged==false)
  {
    // do stuff
  }
   _sizeChanged=true;
}

But is is not enough , because you should change its value again somewhere else. if you do not change its value (for example to false somewhere else) it will never pass the 'if' condition again. So the question is, where you should change its value.

I think you can change the value at MouseButtonUp event, since resizing is done with the mouse.

You can use a boolean to determine whether or not to handle your event.

private bool m_handleResizeEvent;
private void HandleResize(object sender, EventArgs e)
{
    if (m_handleResizeEvent)
    {
         m_handleResizeEvent = false;
         // perform your resize here
         m_handleResizeEvent = true;
    }
}

Turns out it was the SizeToContent="Width" property in my Window's XAML that was causing the SizeChanged to be called multiple times. Removing this property fixed my issue and allowed me to resize the window without the event being fired multiple times. Thanks everyone else for your answers and input!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM