![](/img/trans.png)
[英]Bringing front a user control by a button which is located in another user control
[英]Bring the front user control with a button which is inside in another user control
我有一个表单和一个至少 6 个用户控件(每个 UC 都有一个按钮到 go 到下一个 UC)
我想知道如何从一个 UC 到另一个 UC 的 go 的架构。
表格代码:
public partial class TestProgram : Form
{
public TestProgram()
{
InitializeComponent();
UC21.BringToFront();
}
private void TestProgram_Load(object sender, EventArgs e)
{
UC21.Hide();
UC31.Hide();
UC41.Hide();
UC51.Hide();
UC61.Hide();
UC71.Hide();
UC81.Hide();
}
}
UC1 代码:
public partial class UC1 : UserControl
{
public UC2 UC2{ get; set; }
public UC1()
{
InitializeComponent();
}
private void NextPageBut_Click(object sender, EventArgs e)
{
UC2.BringToFront();
}
}
我认为如果你把它留给你的主窗体来决定下一步是什么而不是在每个用户控件中会更容易。 这使得移动它们或添加一个新的变得不那么麻烦。 我在这里滥用主窗体作为控制器/演示者。
UserControls 被添加到表单的 Controls 集合中。 如果我们不使用BringToFront,而只使用Hide and Show,我们可以让主窗体找到当前显示的用户控件(因为它的Visible 属性设置为true),然后隐藏那个并显示下一个用户控件。 UserControl 具有 Parent 属性,我们可以将其转换为主窗体,以便我们可以在其公共接口上调用方法。
这是 Next 按钮的 click 事件中的代码:
public partial class UC1 : UserControl
{
public UC1()
{
InitializeComponent();
}
private void NextPageBut_Click(object sender, EventArgs e)
{
// get and cast to the parent form
var tpf = (TestProgram) this.Parent;
// tell the mainform we want to go Next
tpf.Next();
}
}
此方法循环控制控件,同时保持 state 来决定要采取的操作。
// our various states
enum NextState {
Start = 0,
ShowOne,
Done,
}
public void Next()
{
NextState state = NextState.Start;
// loop over controls
// if you want to
foreach(var ctl in Controls)
{
// find the UserControl ones
if (ctl is UserControl)
{
var uc = (UserControl) ctl;
// based on our state ...
switch(state)
{
case NextState.Start:
// hide and do the next state
if (uc.Visible)
{
uc.Hide();
state = NextState.ShowOne;
}
break;
case NextState.ShowOne:
// show and do the next state
uc.Show();
state = NextState.Done;
break;
default:
// do nothing
break;
}
}
}
if (state != NextState.Done) {
// nothing got set
// show the first one?
// something else?
}
}
如果您真的想使用 BringToFront,那么您必须更加小心,并且可能执行 SendToBack 以维护 Controls 集合中的顺序。 或者将第二个集合与您的用户控件一起使用,并相应地调整 Next 方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.