切断文本并在WinG的PropertyGrid中显示三个点

时间:2018-01-10 05:41:43

标签: winforms propertygrid

我想剪切多余的文字并显示三个点(...),当用户点击单元格时,必须显示外翻。如何计算属性网格单元格的宽度并剪切文本。任何帮助都将不胜感激。

附上图片以供说明

Instead of this

I would like to achieve this

and it should vary according to the cell size

1 个答案:

答案 0 :(得分:1)

属性网格不允许这样做,您无法使用任何官方方式对其进行自定义。

但是,这里有一些似乎有效的示例代码。它使用TypeConverter来减少网格大小的值。

使用时需要您自担风险,因为它依赖于PropertyGrid的内部方法,可能会对性能产生影响,因为它需要在每次调整大小时刷新整个网格。

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();

        // note this may have an impact on performance
        propertyGrid1.SizeChanged += (sender, e) => propertyGrid1.Refresh();

        var t = new Test();
        t.MyStringProperty = "The quick brown fox jumps over the lazy dog";
        propertyGrid1.SelectedObject = t;
    }

}

public class AutoSizeConverter : TypeConverter
{
    public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
    {
        if (value == null)
            return null;

        // small trick to get PropertyGrid control (view) from context
        var view = (Control)context.GetService(typeof(IWindowsFormsEditorService));

        // bigger trick (hack) to get value column width & font
        int width = (int)view.GetType().GetMethod("GetValueWidth").Invoke(view, null);
        var font = (Font)view.GetType().GetMethod("GetBoldFont").Invoke(view, null); // or GetBaseFont

        // note: the loop is not super elegant and may probably be improved in terms of performance using some of the other TextRenderer overloads
        string s = value.ToString();
        string ellipsis = s;
        do
        {
            var size = TextRenderer.MeasureText(ellipsis, font);
            if (size.Width < width)
                return ellipsis;

            s = s.Substring(0, s.Length - 1);
            ellipsis = s + "...";
        }
        while (true);
    }
}

public class Test
{
    // we use a custom type converter
    [TypeConverter(typeof(AutoSizeConverter))]
    public string MyStringProperty { get; set; }
}

这是结果(支持调整大小):

enter image description here