当用户在WindowsForms设计器上删除 TextBox 控件时,设计器只显示两个大小调整选择器来调整控件的宽度:
...除非手动启用TextBox.MultiLine
属性。
但是如果我们添加RichTextBox
,它会显示8个大小选择器:
...即使启用了RichTextBox.MultiLine
属性。
我想要做的是将RichTextBox
类子类化,以模仿TextBox
默认设计时的大小调整行为,这意味着如果{{1},则防止高度/角大小调整不是多线。
确切地说,我想在设计时删除/隐藏高度和角度大小选择器,因此子类RichTextBox
应该只显示两个大小选择器来调整控件的宽度,就像在RichTextBox
上面的图片。
我知道 the methodology to override SetBoundsCore
method 以防止在设计时调整高度,但是我想比那个解决方案更远一点,因为该解决方案确实不要删除那些大小选择器...而只是让大小选择器可见是一个丑陋和令人困惑的行为在设计时。
我查看了官方TextBox
类源代码以查看 what happens when the TextBox.MultiLine
property value is changed ,但我没有看到任何相关信息。
也许涉及分配给TextBox
类(DesignerAttribute()
)的TextBox
类,也许是谁在设计时确定了大小调整行为?在这种情况下我能做什么做和怎么做?。
答案 0 :(得分:2)
这些称为大小调整句柄,由与控件关联的设计器中的SelectionRules()
方法确定。需要注意的一点是,常规TextBox
的默认值为MultiLine = False
,但与RichTextBox
相反。
您在参考源中找不到任何相关内容的原因是System.Windows.Forms.Design.TextBoxDesigner
为internal
/ Friend
。另请注意,更改MultiLine
属性会导致重新创建控件(源中为RecreateHandle();
)。
Imports System.Windows.Forms.Design
<Designer(GetType(RTBElektroDesigner))>
Public Class RTBElektro
Inherits RichTextBox
Public Sub New()
End Sub
End Class
Public Class RTBElektroDesigner
Inherits System.Windows.Forms.Design.ControlDesigner
Public Overrides ReadOnly Property SelectionRules() As SelectionRules
Get
Dim rtb = TryCast(MyBase.Control, RTBElektro)
If rtb Is Nothing Then
Return MyBase.SelectionRules
Else
If rtb.Multiline Then
Return SelectionRules.AllSizeable Or
SelectionRules.Moveable
Else
Return SelectionRules.LeftSizeable Or
SelectionRules.RightSizeable Or
SelectionRules.Moveable
End If
End If
End Get
End Property
End Class
结果:
答案 1 :(得分:1)
此行为由TextBoxBaseDesigner实现。也是RichTextBoxDesigner的基类,因此您对设计人员非常满意。这里缺少的是AutoSize属性,RichTextBox隐藏它。将Multiline属性更改为False时,需要将其设置为True。你不能从设计师那里做到这一点,因为它是隐藏的,默认值是False。
通过从RichTextBox派生自己的类,可以轻松解决这个问题:
using System;
using System.ComponentModel;
using System.Windows.Forms;
class RichTextBoxEx : RichTextBox {
public RichTextBoxEx() {
base.AutoSize = true;
base.Multiline = false;
}
[DefaultValue(true), Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
public override bool AutoSize {
get => base.AutoSize;
set => base.AutoSize = value;
}
[DefaultValue(false)]
public override bool Multiline {
get => base.Multiline;
set {
base.Multiline = value;
base.AutoSize = !base.Multiline;
}
}
}