C# 设计时带有水平文本的垂直选项卡控件
一个明显的遗漏似乎是,在采用这种方法之后:C# 设计时带有水平文本的垂直选项卡控件,c#,vb.net,winforms,tabcontrol,C#,Vb.net,Winforms,Tabcontrol,一个明显的遗漏似乎是,在采用这种方法之后: 这也是Microsoft推荐的: 在设计时,选项卡上没有文本,因此进一步的开发和支持成为一场噩梦 有没有办法使选项卡文本也在设计时显示?您需要对TabControl进行子类化,并覆盖OnDrawItem。下面是一个例子: Public Class UITabControl Inherits TabControl Protected Overrides Sub OnDrawItem(e As DrawItemEventAr
有没有办法使选项卡文本也在设计时显示?您需要对
TabControl
进行子类化,并覆盖OnDrawItem
。下面是一个例子:
Public Class UITabControl
Inherits TabControl
Protected Overrides Sub OnDrawItem(e As DrawItemEventArgs)
Using brush As New SolidBrush(Me.ForeColor)
Using format As New StringFormat() With {.LineAlignment = StringAlignment.Center}
Select Case Me.Alignment
Case TabAlignment.Left
format.Alignment = StringAlignment.Near
Case TabAlignment.Top
format.Alignment = StringAlignment.Far
End Select
format.FormatFlags = (format.FormatFlags Or StringFormatFlags.NoWrap)
Dim rect As Rectangle = e.Bounds
rect.X += 3
rect.Width -= 6
e.Graphics.DrawString(Me.TabPages(e.Index).Text, Me.Font, brush, rect, format)
End Using
End Using
MyBase.OnDrawItem(e)
End Sub
End Class
只需创建自己的控件,以便自定义图形在设计时也可以工作。向项目中添加一个新类并粘贴如下所示的代码。编译。将新控件从工具箱顶部拖到窗体上。我稍微调整了一下,使它不那么花哨
using System;
using System.Drawing;
using System.Windows.Forms;
class VerticalTabControl : TabControl {
public VerticalTabControl() {
this.Alignment = TabAlignment.Right;
this.DrawMode = TabDrawMode.OwnerDrawFixed;
this.SizeMode = TabSizeMode.Fixed;
this.ItemSize = new Size(this.Font.Height * 3 / 2, 75);
}
public override Font Font {
get { return base.Font; }
set {
base.Font = value;
this.ItemSize = new Size(value.Height * 3 / 2, base.ItemSize.Height);
}
}
protected override void OnDrawItem(DrawItemEventArgs e) {
using (var _textBrush = new SolidBrush(this.ForeColor)) {
TabPage _tabPage = this.TabPages[e.Index];
Rectangle _tabBounds = this.GetTabRect(e.Index);
if (e.State != DrawItemState.Selected) e.DrawBackground();
else {
using (var brush = new System.Drawing.Drawing2D.LinearGradientBrush(e.Bounds, Color.White, Color.LightGray, 90f)) {
e.Graphics.FillRectangle(brush, e.Bounds);
}
}
StringFormat _stringFlags = new StringFormat();
_stringFlags.Alignment = StringAlignment.Center;
_stringFlags.LineAlignment = StringAlignment.Center;
e.Graphics.DrawString(_tabPage.Text, this.Font, _textBrush, _tabBounds, new StringFormat(_stringFlags));
}
}
}
由于您链接到我的问题,我认为最好通知您我的问题线程的更新 为了编程社区的利益,我上传了我的控件代码 这是运行时控件的屏幕截图。
它具有完整的设计时支持、自动调整选项卡大小(高达128px宽)以及选项卡图标
代码可从下载。+1。虽然我更喜欢@HansPassant的解决方案,但渐变会变硬。您有没有理由使用
Font.Height*3/2
来调整ItemSize
属性的高度?我认为使用会是一种更好的方式。不是特别好,它只是为了在标签上留下足够的空白。随便挑吧,好的。我的好奇心现在已经满足了。在我的实现中,我使用了TextRenderer.MeasureText
中的高度,然后添加了Padding.Y
值。我这样做是因为它使我的自定义控件与标准的TabControl
一致。谢谢。如果您概述了自定义控件的基本属性以及使用它的原因,或者在回答中添加了一些代码,那么它可能会对其他开发人员有所帮助。否则看起来像广告(即使产品是免费的)。请注意,在文件共享上发布代码是不可靠的。最好创建一个开源项目(例如,在GitHub上),这样人们就可以扩展您的创建,并且从现在起两年内不会丢失它。