Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF SelectionChanged event do the action before tab change

Tags:

c#

wpf

i have SelectionChanged event in my WPF aplication. i want that when the tab is change to do some action but first i want the tab to visualy change before the action starts. i am using background worker to do the job. my code is:

    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
    }
like image 771
user3719173 Avatar asked Jun 10 '26 08:06

user3719173


1 Answers

Your problem is that your code is running synchronously. Therefore, every line of your Tab_SelectionChanged event handler will run before you will see the TabItem change. To fix this problem, you just need to run your long running process asynchronously. One of the simplest ways to do that is this:

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
}

The parameter input parameter is optional... just remove it if you don't need it.

like image 142
Sheridan Avatar answered Jun 12 '26 21:06

Sheridan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!