这是一个不依赖于直接使用私有方法或反射的方法。但它仍然使用未记录的接口。
在 .NET 4.0 中,PropertyGrid.Controls 集合包含 4 个控件。 PropertyGrid.Controls.item(2) 是一个未记录的 PropertyGridView (与使用反射的答案相同)。属性PropertyGridView.LabelRatio 调整列的相对宽度。 LabelRatio 的范围看起来是 1.1 到 9。较小的值使左列更宽。
我知道在您最初显示控件之前设置LabelRatio 有效。但是,我不确定一旦控件已显示,您需要做什么才能使其生效。您可以通过 Google MoveSplitterTo 查找 .NET 源代码并查看 PropertyGridView 的源代码以获取更多详细信息。涉及到的计算和运算看起来有些复杂,我没有详细分析。
LabelRatio 最初设置为 2(即将可用的 PropertyGrid 宽度分成两半)。将其设置为 3 表示三分之一,4 表示四分之一。
代码需要导入 System.Reflection
Public Sub MoveVerticalSplitter(grid As PropertyGrid, Fraction As Integer)
Try
Dim info = grid.[GetType]().GetProperty("Controls")
Dim collection = DirectCast(info.GetValue(grid, Nothing), Control.ControlCollection)
For Each control As Object In collection
Dim type = control.[GetType]()
If "PropertyGridView" = type.Name Then
control.LabelRatio = Fraction
grid.HelpVisible = True
Exit For
End If
Next
Catch ex As Exception
Trace.WriteLine(ex)
End Try
End Sub
将 PropertyGrid 底部的描述窗格的大小更改为文本行
Public Sub ResizeDescriptionArea(grid As PropertyGrid, lines As Integer)
Try
Dim info = grid.[GetType]().GetProperty("Controls")
Dim collection = DirectCast(info.GetValue(grid, Nothing), Control.ControlCollection)
For Each control As Object In collection
Dim type = control.[GetType]()
If "DocComment" = type.Name Then
Const Flags As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic
Dim field = type.BaseType.GetField("userSized", Flags)
field.SetValue(control, True)
info = type.GetProperty("Lines")
info.SetValue(control, lines, Nothing)
grid.HelpVisible = True
Exit For
End If
Next
Catch ex As Exception
Trace.WriteLine(ex)
End Try
End Sub