0

我在 WinForms 应用程序中使用 MVP 监督演示者模式。我有一个带有 aTabControl和多个TabPages 的视图。我需要延迟加载每个标签页的内容,因为在尝试填充整个视图时存在明显的滞后。

我希望挂钩 TabPage.GotFocus 事件并在选择给定选项卡但似乎不起作用时提供处理程序。所以我不得不使用TabControl.SelectedIndexChanged事件和 switch 语句来让它工作。必须放入 switch 语句是一个真正的痛苦。有没有办法避免 switch 语句?

public partial class Form1 : Form
{
    public event EventHandler TabPage1Selected;

    public event EventHandler TabPage2Selected;

    public event EventHandler TabPage3Selected;


    public Form1()
    {
        InitializeComponent();
        this.tabControl1.SelectedIndexChanged += tabControl1_SelectedIndexChanged;

        this.tabPage1.GotFocus += tabPage1_GotFocus; //Doesn't work!
    }

    private void tabPage1_GotFocus(object sender, EventArgs e)
    {
        Debug.WriteLine("event fired for tabpage1");
    }

    private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
    {
        Debug.WriteLine("Raising tab selected event");
        EventHandler h = null;
        switch (this.tabControl1.SelectedIndex)
        {
            case 0:
                h = this.TabPage1Selected;
                break;
            case 1:
                h = this.TabPage2Selected;
                break;
            case 2:
                h = this.TabPage3Selected;
                break;
            default:
                break;
        }
        if (h != null) h(this, new EventArgs());
    }    
}
4

2 回答 2

1

You could subclass TabItem for each TabItem you want to add and implement a .Load() method on each one. Apart from subclassing or some overly complex dictionary/delegate solution, I don't think you'll avoid some form of flow control. Switch is the most appropriate form of flow control here.

I would look at finding something better than index to switch on - some sort of tab id or name. You don't want to have to rewrite this code if you rearrange your tabs later on.

于 2013-02-25T03:22:56.403 回答
0

您可以使用 Enter 事件。在属性 | 中选择 TabPage 您可以在设计器中的事件列表中设置 Enter 事件/或者您可以通过编程方式设置事件。每次 TabPage 获得焦点时都会触发 enter…

public Form1()
{
    InitializeComponent();

    // I set tabPage1 & 2 event w/ the designer
    tabPage3.Enter += tabPage3_Enter;
}

private void tabPage1_Enter(object sender, EventArgs e)
{
    Debug.WriteLine("tabPage1_Enter");
}

private void tabPage2_Enter(object sender, EventArgs e)
{
    Debug.WriteLine("tabPage2_Enter");
}

private void tabPage3_Enter(object sender, EventArgs e)
{
    Debug.WriteLine("tabPage3_Enter");
}
于 2013-02-25T05:07:54.047 回答