Windows 窗体 C# 通过代码更改用户控件 [英] Windows form C# change user control by code
问题描述
我有一个 windows 窗体,我不想让任何其他 windows 窗体只是一个 windows 窗体和不同的用户控件如何在用户控件之间进行更改,例如隐藏一个并以编程方式显示另一个用户控件?
I have a windows form and i dont want to make any other windows forms just one windows form and different user controls how can i change between user controls for example hide one and show the other user control programmatically ?
private void Btt_info_Click(object sender, EventArgs e)
{
Frm_Main frm_main = new Frm_Main();
frm_main.Controls["panel1"].Controls.Clear();
UC_Info uc_info = new UC_Info();
frm_main.Controls["panel1"].Controls.Add(uc_info);
}
我添加了这个但它不起作用
i added this but it doesnt work
推荐答案
添加一个容器控件(如果我没记错的话,工具箱中有一个容器部分?),就像一个面板.为您想要动态切换的内容创建用户控件.所以像'HomePage'用户控件和'LoginPage'用户控件.将要显示的用户控件动态添加到容器中.需要时,将其从容器中移除并添加不同的用户控件:
Add a container control (if I remember correctly, there's a containers section in the toolbox?), like a panel. Create usercontrols for what you want to dynamically switch around. So make like a 'HomePage' usercontrol and a 'LoginPage' usercontrol. Dynamically add the usercontrol that you want to display to the container. WHen you want, remove it from the container and add a different usercontrol:
Panel myPanel = new Panel();
LoginPage ctlLoginPage = new LoginPage();
HomePage ctlHomePage = new HomePage();
//add the loginpage to the panel first
myPanel.Controls.Add(ctlLoginPage);
...do stuff...
//remove whatever control is currently in the Panel
myPanel.Controls.Clear();
//add the other control, the HomePage control instead now
myPanel.Controls.Add(ctlHomePage);
..do other stuff...
我通常这样做是为了让表单本身保持打开状态,以添加可能在不同页面"之间共享的通用控件和内容.
I usually do it this way so you leave your form itself open to add common controls and stuff that might be shared between your different 'pages'.
请注意,我通常会在设计器中添加面板,而不是在代码中动态创建它.这只是一个例子.
Note that I normally would add the panel in the designer and not create it dynamically in the code. This was just an example.
主窗体和用户控件之间的交互可以通过几种不同的方式进行处理,我并不是说这些方法中的任何一种都是正确的方法.
The interaction between your mainform and usercontrols can be handled in a few different ways, and I am not saying that any of these is the correct method.
- 您在 Mainform 上为 Panel 创建一个静态属性,以便您可以随时访问它以交换您的控件.
在这个例子中,我还将为其添加一个静态方法
In this example I'll also add a static method for it
enum PanelControlsEnum {HomePage, LoginPage};
public static Panel MyContainerPanel {get;set;}
public static void SwitchPanelControls(PanelControlsEnum selControl){
..put your switch panels code here..
}
然后在您的用户控件中调用一个预定义的方法,例如:
Then inside your usercontrol you call a predefined method, something like:
MainForm.SwitchPanelControls(PanelControlsEnum.HomePage);
- 另一种方法是在你的主窗体上绑定按钮点击事件而不是表单内部.
像这样:
HomePage ctlHomePage = new HomePage();
ctlHomePage.Click += MyClickEvent;
myPanel.Controls.Add(ctlHomePage)
...
private void MyClickEvent(object sender, RoutedEventArgs e)
{
..switch user control code here...
}
这篇关于Windows 窗体 C# 通过代码更改用户控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!