【问题标题】:Chop the text and display three dots in PropertyGrid of winforms在winforms的PropertyGrid中截取文字并显示三个点
【发布时间】:2018-01-10 05:41:43
【问题描述】:

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

附上图片说明

Instead of this

I would like to achieve this

and it should vary according to the cell size

【问题讨论】:

  • 您需要找到正确的属性。在屏幕截图中查找根据需要处理属性的控件的源代码,并查看属性上的属性。

标签: winforms propertygrid


【解决方案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; }
}

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

【讨论】:

  • 嗨。是否也可以具有 ConvertFrom 功能?用户也想编辑数据
  • 您必须覆盖 CanConvertFrom 并返回 true,但问题是原始字符串已被截断,因此您必须将其存储在某个位置,例如对象的另一个属性中,可能是隐藏的
  • 嗨,西蒙,感谢您的回答。你能帮我解决这个问题吗?当用户单击单元格时,应该有 3 个点,它应该显示整个字符串,用户可以进行更改。当用户离开单元格时,我们将再次截断更新的字符串并用三个点显示
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-08
  • 2013-10-24
  • 2022-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多