我想你想的東西像下面
更新 分配器舉動排除
using System;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
[Docking(System.Windows.Forms.DockingBehavior.Ask)]
public partial class MyUserControl : UserControl
{
TextBox textBox1;
TextBox textBox2;
public MyUserControl()
{
BackColor = Color.White;
this.textBox1 = new TextBox();
Controls.Add(this.textBox1);
this.textBox2 = new TextBox();
Controls.Add(this.textBox2);
}
protected override void OnParentChanged(EventArgs e)
{
base.OnParentChanged(e);
if (Parent is Panel)
{
if ((Parent as Panel).Parent is SplitContainer)
{
Parent.Resize += Parent_Resize;
AlignChildren();
}
}
}
SplitContainer SplitContainer
{
get
{
return Parent.Parent as SplitContainer;
}
}
Orientation lastOrientation;
void Parent_Resize(object sender, EventArgs e)
{
if (Parent == null || IsDisposed)
{
Parent.Resize -= Parent_Resize;
return;
}
if (lastOrientation != SplitContainer.Orientation)
{
AlignChildren();
}
lastOrientation = SplitContainer.Orientation;
}
void AlignChildren()
{
switch (SplitContainer.Orientation)
{
case Orientation.Horizontal:
this.textBox1.Location = new Point(10, 10);
this.textBox2.Location = new Point(this.textBox1.Right + 5, 10);
break;
case Orientation.Vertical:
this.textBox1.Location = new Point(10, 10);
this.textBox2.Location = new Point(10, this.textBox1.Bottom + 5);
break;
}
}
}
}
將這個控制在上Designer中的SplitContainer。更改SplitContainer的方向屬性。在運行時也可以嘗試切換按鈕。
更新2
您也可以創建自己的SplitContainer
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public class MySplitContainer : System.Windows.Forms.SplitContainer
{
public new Orientation Orientation
{
get
{
return base.Orientation;
}
set
{
if (base.Orientation != value)
{
base.Orientation = value;
OnOrientationChanged();
}
}
}
protected virtual void OnOrientationChanged()
{
if (OrientationChanged != null)
{
OrientationChanged(this, EventArgs.Empty);
}
}
public event EventHandler OrientationChanged;
}
}
怎樣的方向改變? – CodingYoshi
@CodingYoshi,給這個問題增加了一些信息。希望它澄清情況。 – elimad
爲什麼你需要在設計時對它做出反應? – CodingYoshi