【问题标题】:C# WinForms Need to ensure UserControl sizeC# WinForms 需要保证 UserControl 大小
【发布时间】:2021-02-18 02:40:02
【问题描述】:

我有从 UserControl 继承的自定义控件。我需要确保它是平方的。 所以,我需要这样的东西:

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

但是我应该在哪里实现这个逻辑呢?我不能在 OnResize 中执行此操作,因为它会导致递归调用并导致 Visual Studio 在设计模式下或应用程序在运行时崩溃。

【问题讨论】:

  • onresize 不应导致循环崩溃。其他一些因素可能会导致这种情况
  • 正如@mw509 所说,OnResize 不会导致这种情况。但是,它应该触发 once 或 twice,这取决于您是否偶然调整平方大小。

标签: c# winforms user-controls resize custom-controls


【解决方案1】:

为了保持平方的外观,我建议覆盖 OnLayout 而不是 OnResize,后者可以在调整 UserControl 大小时多次调用表单设计器或在运行时。
OnLayout 在首次创建 UC 时被多次调用(它必须在初始化时多次设置大小)。

您还需要检查 UserControl 的 Size 是缩小还是放大:

  • 如果 UC 放大,您将平方大小设置为 Math.Max(Width, Height)
  • 如果缩小 UC,则将平方大小设置为 Math.Min(Width, Height)

您已执行此检查,否则,当 - 例如 - 美国扩大时,您将无法将其调整为低于 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));
    }
}

【讨论】:

    猜你喜欢
    • 2011-01-11
    • 1970-01-01
    • 2010-12-02
    • 1970-01-01
    • 2011-08-14
    • 1970-01-01
    • 1970-01-01
    • 2016-12-13
    • 1970-01-01
    相关资源
    最近更新 更多