[英]Override AutoSize for derived Label Control in C#
我正在尝试扩展System.Windows.Forms.Label类以支持垂直绘制的文本。 为此,我创建了一个名为MyLabelOrientation的新属性,用户可以将其设置为Horizontal或Vertical。 当用户更改此设置时,将交换宽度和高度的值以将控件调整为新的方向。 最后,我重写了OnPaint函数以绘制标签。
我也想扩展此控件的AutoSize属性,以便我的Label自动调整其包含的文本的大小。 对于水平方向,基本功能为我实现了此功能。 对于垂直方向,我创建了一个Graphics对象,并将控件的高度设置为从Graphics.MeasureString(Text,Font)返回的SizeF对象的宽度。 您可以在下面看到我正在使用的代码示例。
using System;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel.Design;
using System.Windows.Forms.Design;
public class MyLabel : Label
{
public enum MyLabelOrientation {Horizontal, Vertical};
protected MyLabelOrientation m_orientation = MyLabelOrientation.Horizontal;
[Category("Appearance")]
public virtual MyLabelOrientation Orientation
{
get { return m_orientation; }
set
{
m_orientation = value;
int temp = Height;
Width = Height;
Height = temp;
Refresh();
}
}
private Size ResizeLabel()
{
Graphics g = Graphics.FromHwnd(this.Handle);
SizeF newSize = g.MeasureString(Text, Font);
if (m_orientation == MyLabelOrientation.Horizontal)
Width = (int)newSize.Width;
else
Height = (int)newSize.Width;
}
protected override void OnPaint(PaintEventArgs e)
{
Brush textBrush = new SolidBrush(this.ForeColor);
if (m_orientation == LabelOrientation.Vertical)
{
e.Graphics.TranslateTransform(Width, 0);
e.Graphics.RotateTransform(90);
e.Graphics.DrawString(Text, Font, textBrush, Padding.Left, Padding.Top);
}
else
{
base.OnPaint(e);
}
}
}
但是,将AutoSize设置为true似乎可以防止和/或覆盖对控件大小的任何更改。 这意味着我想更改标签的方向时无法更改宽度或高度。 我想知道是否可以覆盖此行为,以便可以测试是否设置了AutoSize,然后根据控件的方向调整控件的大小。
我之前没有做过此操作,我相信您理论上可以覆盖属性声明(通过new
关键字)并在继续操作之前检查方向:
override public bool AutoSize
{
set
{
if( /* orientation is horizontal */ )
{
base.AutoSize = value;
}
else
{
// do what you need to do
}
}
}
如果认为解决方案是重写OnResize
本身:
protected override void OnResize(EventArgs e)
{
if (AutoSize)
{
// Perform your own resizing logic
}
else
OnResize(e);
}
我知道这是一个非常老的问题,但是今天我偶然发现了这个问题,并且想知道如何做同样的事情。
我对这个问题的解决方案是重写GetPreferredSize(Size proposedSize)
方法。 我使用了一个按钮类,除了文本之外,该类还包含一个箭头,当然,使用AutoSize属性没有考虑到该文本,因此我添加了额外的空间,对我来说很好用。
考虑到更改方向或切换宽度和高度的问题,您可以完全更改首选大小的计算方式。
public override Size GetPreferredSize(Size proposedSize)
{
Size s = base.GetPreferredSize(proposedSize);
if (AutoSize)
{
s.Width += 15;
}
return s;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.