开发者

PreferredSize property doesn't match GetPreferredSize

开发者 https://www.devze.com 2023-02-24 22:16 出处:网络
I am trying to write a menu item control that will AutoSize based on the length of text it contains (like the Label control).

I am trying to write a menu item control that will AutoSize based on the length of text it contains (like the Label control).

To do this, I overrided the GetPreferredSize method to calculate the length of the text:

    public override Size GetPreferredSize(Size proposedSize)
    {
        Size size = TextRenderer.MeasureText(this.Text, this.Font);
        int w = size.Width +开发者_开发技巧 this.Padding.Left + this.Padding.Right;
        int h = size.Height + this.Padding.Top + this.Padding.Bottom;
        return new Size(w, h);
    }

I then add a bunch of these controls to a containing menu control and try to position them based on the size above:

            if (item.AutoSize)
            {
                item.Size = item.PreferredSize;
            }

            item.Left = _Left;
            item.Top = _Top;

            if (this.MenuOrientation == Orientation.Vertical)
            {
                _Top += item.Size.Height;
            }
            else
            {
                _Left += item.Size.Width;
            }

            this.Controls.Add(item);

However, the sizes returned by PreferredSize and GetPreferredSize aren't the same. For one string, GetPreferredSize returns {Width=147, Height=27}, but PreferredSize returns {Width=105, Height=21}. Because of this the controls overlap instead of appearing beside one another.

I tried overriding MinimumSize instead of GetPreferredSize, but that also got scaled down from what I calculated.

So my question is, what is the correct way to do this? I'd also like to understand the way that AutoSize, PreferredSize, MinimumSize, and MaximumSize are meant to interact. MSDN is little help on this.

0

精彩评论

暂无评论...
验证码 换一张
取 消