【发布时间】:2018-01-10 05:41:43
【问题描述】:
我想剪切多余的文本并显示三个点(...),当用户单击单元格时,必须显示所有内容。如何计算属性网格单元格的宽度并剪切文本。任何帮助将不胜感激。
附上图片说明
【问题讨论】:
-
您需要找到正确的属性。在屏幕截图中查找根据需要处理属性的控件的源代码,并查看属性上的属性。
标签: winforms propertygrid
我想剪切多余的文本并显示三个点(...),当用户单击单元格时,必须显示所有内容。如何计算属性网格单元格的宽度并剪切文本。任何帮助将不胜感激。
附上图片说明
【问题讨论】:
标签: winforms propertygrid
属性网格不允许这样做,您不能使用任何官方方式对其进行自定义。
但是,这里有一些似乎可以工作的示例代码。它使用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; }
}
这是结果(支持调整大小):
【讨论】: