简体   繁体   English

SizeChanged事件被递归触发

[英]SizeChanged event being fired recursively

I have a SizeChanged event in one of my windows. 我的一个窗口中有一个SizeChanged事件。 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. 用户控件之一的Width表现有趣,所以我决定在SizeChanged事件中静态设置窗口的宽度。 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. 如果您不更改其值(例如,在其他地方更改为false),它将永远不会再通过'if'条件。 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. 我认为您可以更改MouseButtonUp事件的值,因为调整大小是使用鼠标完成的。

You can use a boolean to determine whether or not to handle your event. 您可以使用boolean来确定是否处理事件。

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. 原来是导致我的Window的XAML中的SizeToContent =“ Width”属性导致多次调用SizeChanged。 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! 感谢其他人的回答和输入!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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