1: void LabelEx_TextChanged(object sender, EventArgs e)
2: {
3: //记录下当前的高度
4: int oh = this.Height;
5:
6: //文字变化了,那就改变一下当前的大小
7: System.Drawing.Size ps = GetPreferredSize(this.Size);
8:
9: //这里构造一个新的Size对象,目的是使用原始的宽度。原因嘛,见上面
10: this.Size = new System.Drawing.Size(this.Width, ps.Height);
11:
12: if (this.Parent != null && AutoResizeParent)
13: {
14: //调整容器大小
15: this.Parent.Size = new System.Drawing.Size(this.Parent.Width, ps.Height - oh + this.Parent.Height);
16: }
17: }
1: internal class LabelEx : System.Windows.Forms.Label
2: {
3: public LabelEx()
4: : base()
5: {
6: //关闭AutoSize
7: this.AutoSize = false;
8:
9: //捕捉事件
10: this.TextChanged += new EventHandler(LabelEx_TextChanged);
11: this.SizeChanged += new EventHandler(LabelEx_SizeChanged);
12: }
13:
14: //记录原始的宽度
15: int _oldw;
16:
17: void LabelEx_SizeChanged(object sender, EventArgs e)
18: {
19: //如果宽度没变,那就返回
20: if (this.Width == _oldw) return;
21:
22: //重新计算高度
23: LabelEx_TextChanged(null, null);
24:
25: //记录
26: _oldw = this.Width;
27: }
28:
29: /// <summary>
30: /// 重写AutoSize属性,防止AutoSize再被打开
31: /// </summary>
32: public override bool AutoSize
33: {
34: get
35: {
36: return false;
37: }
38: }
39:
40: /// <summary>
41: /// 是否自动调整父控件
42: /// </summary>
43: public bool AutoResizeParent { get; set; }
44:
45: void LabelEx_TextChanged(object sender, EventArgs e)
46: {
47: //记录下当前的高度
48: int oh = this.Height;
49:
50: //文字变化了,那就改变一下当前的大小
51: System.Drawing.Size ps = GetPreferredSize(this.Size);
52:
53: //这里构造一个新的Size对象,目的是使用原始的宽度。原因嘛,见上面
54: this.Size = new System.Drawing.Size(this.Width, ps.Height);
55:
56: if (this.Parent != null && AutoResizeParent)
57: {
58: //调整容器大小
59: this.Parent.Size = new System.Drawing.Size(this.Parent.Width, ps.Height - oh + this.Parent.Height);
60: }
61: }
62: }
撸过