更改 PropertyGrid 描述区域的高度






3.60/5 (4投票s)
如何更改 PropertyGrid 的描述区域高度。
背景
我最近创建了一个使用了 PropertyGrid
的工具。 属性描述往往很长,无法适应控件的描述区域。 我决定在运行时更改描述高度,因为我无法在设计时找到方法来执行此操作。 由于我不知道该如何进行(我的第一个 C# 项目,也是我第一次使用 Visual Studio 7.1),我在网上搜索现有的解决方案。 我未能找到任何 C# 解决方案,但我在 Matthew Cosier 的博客 上找到了一篇 VB 文章,并将其代码改编为我的用途。
使用代码
只需将下面的函数插入到您的代码中并调用它
Private bool ResizeDescriptionArea(ref PropertyGrid grid, int nNumLines)
{
try
{
System.Reflection.PropertyInfo pi = grid.GetType().GetProperty("Controls");
Control.ControlCollection cc = (ControlCollection)pi.GetValue(grid, null);
foreach(Control c in cc)
{
Type ct = c.GetType();
string sName = ct.Name;
if(sName == "DocComment")
{
pi = ct.GetProperty("Lines");
pi.SetValue(c, nNumLines, null);
System.Reflection.FieldInfo fi = ct.BaseType.GetField("userSized",
System.Reflection.BindingFlags.Instance,
System.Reflection.BindingFlags.NonPublic);
fi.SetValue(c, true);
}
}
return true;
}
catch(Exception error)
{
#if(DEBUG)
MessageBox.Show(error.Message, "ResizeDescriptionArea()");
#endif
return false;
}
}
我这样调用它
private void Form1_load(object sender, System.EventArgs e)
{
.
.
.
ResizeDescriptionArea(ref grid1, 6);
}