当文本太长时,在GroupBox中显示省略号?

时间:2015-07-10 13:56:00

标签: c# windows forms winforms

RadioButton和CheckBox具有WrapText属性。启用后,对于控件来说太长的文本会被包装。禁用时,最后会显示省略号。

Label具有AutoElipsis属性,它执行相同的操作,但必须启用省略号才能显示。

如何在GroupBox中强制执行相同的行为?

1 个答案:

答案 0 :(得分:1)

你去了,我为你创建了自定义控件。使用它而不是GroupBox,您还可以通过设计器属性或代码启用/禁用AutoElipsis。

public class ElipsisGroupBox : GroupBox
{
    private string _tempText;
    private bool _isElipsisOn;

    public ElipsisGroupBox () : base()
    {
        _tempText = string.Empty;
        _isElipsisOn = false;
    }

    protected override void OnResize(EventArgs e)
    {
        base.OnResize(e);

        if (this.AutoElipsis)
        {
            _tempText = base.Text;
            if (_tempText.Length == 0 || base.Width == 0)
                return;

            int i = _tempText.Length;

            string textToCheck = _isElipsisOn ? _tempText : _tempText + "...";

            _isElipsisOn = false;
            while (TextRenderer.MeasureText(textToCheck, base.Font).Width > (base.Width - 14))
            {
                _isElipsisOn = true;
                textToCheck = base.Text.Substring(0, --i) + "...";
                if (i == 0)
                    break;
            }

            if (_isElipsisOn)
                _tempText = textToCheck;
        }
    }

    public override string Text
    {
        get
        {
            return this.AutoElipsis && _isElipsisOn ? _tempText : base.Text;
        }
        set
        {
            if (this.AutoElipsis && _isElipsisOn)
                _tempText = value;
            else
                base.Text = value;
        }
    }

    public bool AutoElipsis { get; set; }
}