"ResizeEnd" equivalent for usercontrols
开发者_运维技巧I am writing a UserControl. I want to draw the user control when the resize is done. I am not able to find any event equivalent to "ResizeEnd" of a windows form.
Is there any equivalent event for user controls?
Please note that in this case the parent control of the user control is itself an UserControl, so I cannot convert it (parent user control) into a form. As I am using a framework, I cannot access the form on which this user control will be displayed.
There is no equivalent. A form has a modal sizing loop, started when the user clicks the edge or a corner of the form. Child controls cannot be resized that way, it only sees changes to its Size property.
Solve this by adding a Sizing property to your user control. The form can easily assign it from its OnResizeBegin/End() overrides. Following the Parent property in the UC's Load event until you find the Form is possible too:
public bool Resizing { get; set; }
private void UserControl1_Load(object sender, EventArgs e) {
if (!this.DesignMode) {
var parent = this.Parent;
while (!(parent is Form)) parent = parent.Parent;
var form = parent as Form;
form.ResizeBegin += (s, ea) => this.Resizing = true;
form.ResizeEnd += (s, ea) => this.Resizing = false;
}
}
The Hans solution is working (and it looks like it is the only way to do it), but it's requires these handlers in every form, which using your control (which is not always acceptable).
So, you can use simple workaround, starting timer when resizing occurs. Every time size will be changed your timer will be restarted. And only when there will be no size changes for some time (_timer.Interval) it will invoke ResizeFinished() method.
private Timer _timer;
public MyControl()
{
_timer = new Timer();
_timer.Interval = 500;
_timer.Tick += (sender, e) => ResizeFinished();
}
protected override void OnSizeChanged(EventArgs e)
{
base.OnSizeChanged(e);
_timer.Start();
}
private void ResizeFinished()
{
_timer.Stop();
// Your code
}
As you can see, your code will be invoked only after 500 ms after last size changed invocation.
精彩评论