WPF SelectionChanged事件在更改选项卡之前执行操作

时间:2014-06-12 05:33:26

标签: c# wpf

我的WPF应用程序中有SelectionChanged事件。我希望当更改选项卡以执行某些操作时,但首先我希望选项卡可以在>操作开始之前改变。我正在使用后台工作人员来完成这项工作。我的代码是:

    private void Tab_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (tab1.IsSelected)
        {
            //this line is not working
            tabcontrol.SelectedIndex = 1;
            wNetTest = new BackgroundWorker();
            wNetTest.DoWork += new DoWorkEventHandler(worker_DoWork);
            wNetTest.RunWorkerCompleted += worker_RunWorkerCompleted;
            wNetTest.WorkerReportsProgress = true;
            wNetTest.WorkerSupportsCancellation = true;
            wNetTest.RunWorkerAsync();

        }
    }

    void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        //do the job
    }

1 个答案:

答案 0 :(得分:1)

您的问题是您的代码同步运行。因此,Tab_SelectionChanged事件处理程序的每一行都将在之前运行,您将看到TabItem更改。要解决此问题,您只需要异步运行长时间运行的进程。最简单的方法之一是:

private void Tab_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (tab1.IsSelected)
    {
        //this line is not working
        tabcontrol.SelectedIndex = 1;
        Task.Factory.StartNew(() => LongRunningMethod(parameter));

    }
}

private void LongRunningMethod(object parameter)
{
    // perform long running process here
}

parameter输入参数是可选的...如果您不需要,请将其删除。