using System; using System.Windows.Forms; using System.Drawing; public class MyContainer : ScrollableControl, IContainerControl { private Control activeControl; public MyContainer() { // Make the container control Blue so it can be distinguished on the form. this.BackColor = Color.Blue;
// Make the container scrollable. this.AutoScroll = true; } // Add implementation to the IContainerControl.ActiveControl property. public Control ActiveControl { get { return activeControl; } set { // Make sure the control is a member of the ControlCollection. if(this.Controls.Contains(value)) { activeControl = value; } } } // Add implementations to the IContainerControl.ActivateControl(Control) method. public bool ActivateControl(Control active) { if(this.Controls.Contains(active)) { // Select the control and scroll the control into view if needed. active.Select(); this.ScrollControlIntoView(active); this.activeControl = active; return true; } return false; } }
ContainerControl 表示可用作其他控件的容器的控件并提供焦点管理功能。从该类继承的控件可以跟踪它们包含的活动控件,即使焦点移动到不同容器内的某个位置。ContainerControl 对象为包含的控件提供逻辑边界。容器控件可以捕获 TAB 键按下事件,并将焦点移动到集合中的下一个控件。注意 容器控件不接收焦点;焦点总是设置在被包含控件构成的集合中的第一个子控件上。
通常不直接从该类继承。Form、UserControl 和 UpDownBase 类从 ContainerControl 继承。
下面的示例从 ScrollableControl 类继承,并实现 IContainerControl 接口。将实现添加到 ActiveControl 属性和 ActivateControl 方法
using System.Windows.Forms;
using System.Drawing; public class MyContainer : ScrollableControl, IContainerControl
{
private Control activeControl;
public MyContainer()
{
// Make the container control Blue so it can be distinguished on the form.
this.BackColor = Color.Blue;
// Make the container scrollable.
this.AutoScroll = true;
} // Add implementation to the IContainerControl.ActiveControl property.
public Control ActiveControl
{
get
{
return activeControl;
} set
{
// Make sure the control is a member of the ControlCollection.
if(this.Controls.Contains(value))
{
activeControl = value;
}
}
} // Add implementations to the IContainerControl.ActivateControl(Control) method.
public bool ActivateControl(Control active)
{
if(this.Controls.Contains(active))
{
// Select the control and scroll the control into view if needed.
active.Select();
this.ScrollControlIntoView(active);
this.activeControl = active;
return true;
}
return false;
}
}