简体   繁体   English

C# WinForms 需要保证UserControl的大小

[英]C# WinForms Need to ensure UserControl size

I have custom control inherited from UserControl.我有从 UserControl 继承的自定义控件。 I need to ensure that it is squared.我需要确保它是平方的。 So, I need smth like that:所以,我需要这样的东西:

int side = Math.Max(this.Width, this.Height);
this.Size = new Size(side, side);

But where should I implement this logic?但是我应该在哪里实现这个逻辑? I cannot do it in OnResize because it causes recursive calls and crashes Visual Studio in design mode, or app in runtime.我无法在 OnResize 中执行此操作,因为它会导致递归调用并使设计模式下的 Visual Studio 或运行时的应用程序崩溃。

To keep a squared aspect, I suggest to override OnLayout instead of OnResize , the latter can be called more than once when the UserControl is resized in the Form designer or at run-time.为了保持平方,我建议覆盖OnLayout而不是OnResize ,当在表单设计器中或在运行时调整 UserControl 的大小时,可以多次调用后者。
OnLayout is called multiple times when the UC is first created (it has to, the size is set multiple time in the initialization). OnLayout在第一次创建 UC 时被多次调用(它必须在初始化时多次设置大小)。

You also need to check whether the UserControl's Size is scaled down or up:您还需要检查 UserControl 的 Size 是缩小还是放大:

  • If the UC is scaled up, you set the squared size to Math.Max(Width, Height)如果 UC 放大,则将平方大小设置为Math.Max(Width, Height)
  • If the UC is scaled down, you set the squared size to Math.Min(Width, Height)如果 UC 缩小,则将平方大小设置为Math.Min(Width, Height)

You have perform this check otherwise, when - for example - the US is scaled up, you won't be able to resize it to a value that is lower that Max(Width) or Max(Height) (ie, when scaled up, it won't ever scale down).您已执行此检查,否则,当 - 例如 - 美国被放大时,您将无法将其调整为低于Max(Width)Max(Height) (即,当放大时,它永远不会缩小)。

public partial class MyUserControl : UserControl
{
    int m_Squared = 0;

    public MyUserControl()
    {
        InitializeComponent();
        // Test with and without setting these
        this.MaximumSize = new Size(100, 100);
        this.MinimumSize = new Size(300, 300);
    }

    protected override void OnLayout(LayoutEventArgs e)
    {
        base.OnLayout(e);

        m_Squared = (this.Width > m_Squared || this.Height > m_Squared) 
                  ? Math.Max(this.Width, this.Height) 
                  : Math.Min(this.Width, this.Height);
        this.Bounds = new Rectangle(this.Location, new Size(m_Squared, m_Squared));
    }
}

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

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