一个表单包含多个页面?C# [英] Multiple Pages withing one Form? C#

查看:39
本文介绍了一个表单包含多个页面?C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段时间没有这样做了,所以我不太确定如何做我需要的,但我相信这很简单.

I haven't done this for a while so am not quite sure how to do what I need, but I am sure it is pretty simple.

基本上,我有一个带有导航窗格的表单.我想这样做,当用户单击该窗格上的按钮时,说主页"它会更改表单上的内容,但实际上并没有切换到另一个表单,如果你明白?

Basically, I have a form with a navigation pane. I want to make it so when a user clicks a button on that pane, say 'Home' it changes the content on the form, but doesn't actually switch to another form, if you get me?

正如,我希望导航窗格始终保持原样,我只希望更改表单的内容.它几乎就像 Visual Studio 的工具箱"中的TabControl"工具,尽管我希望它们不是直接位于内容上方的选项卡,而是显示在侧窗格中的按钮.请参阅下图以更好地理解.谢谢!

As in, I would like the navigation pane to stay as it is the entire time and I only want the content of the form to change. It is almost like the 'TabControl' tool in Visual Studio's 'Toolbox' although instead of the tabs being directly above the content, I want them to be buttons displayed in a side pane. See the image below for a better understanding. Thanks!

(无论按下哪个按钮,侧窗格和标题都保持不变,但内容会发生变化.)

(Side pane, and header stays the same regardless on what button is pressed, but the content changes.)

推荐答案

我会使用 UserControl 来实现.单击按钮时会显示一个 UserControl.我将创建一个接口(例如 IView),该接口将由每个声明通用功能的 UserControl 实现,例如一种检查您是否可以从一个功能切换的方法到另一个(如表单的 OnClosing 事件),如下所示:

I'd implement this using UserControls. One UserControl is shown when a button is clicked. I'd create an interface (for example IView) that would be implemented by each UserControl that declares common functionality, like for example a method to check whether you can switch from one to another (like a form's OnClosing event) like this:

public interface IView
{
    bool CanClose();
}

public UserControl View1: IView
{
    public bool CanClose()
    {
       ...
    }
}

public UserControl View2: IView
{
    public bool CanClose()
    {
       ...
    }
}

然后,切换视图很容易:

Then, switching views is quite easy:

private bool CanCurrentViewClose()
{
    if (groupBox1.Controls.Count == 0)
        return true;

    IView v = groupBox1.Controls[0] as IView;
    return v.CanClose();
}

private void SwitchView(IView newView)
{
    if (groupBox1.Controls.Count > 0)
    {
        UserControl oldView = groupBox1.Controls[0] as UserControl;
        groupBox1.Controls.Remove(oldView);
        oldView.Dispose();
    }
    groupBox1.Controls.Add(newView);
    newView.Dock = Dock.Fill;
}

在一个按钮中你可以这样做:

In a button you could do this:

private void btnHome_Click(object sender, EventArgs e)
{
    if (CanCurrentViewClose())
    {
        ViewHome v = new ViewHome();
        // Further initialization of v here

        SwitchView(v);
    }
    else
    {
        MessageBox.Show("Current View can not close!");
    }
}

我已经在很多场合成功地使用了这种方法.

I've successfully used this approach on many occasions.

这篇关于一个表单包含多个页面?C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆