Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TabControl's SelectionChanged event issue

Tags:

c#

wpf

tabcontrol

I am working on WPF and I am creating a userControl which contains a TabControl which has some TabItems.

I need to execute some stuff when the selected tab changes, so, what I tried to do is to use the event myTabControl.SelectionChanged but it was raised many times, even though I only clicked once a TabItem. Then I read this post is-there-selected-tab-changed-event-in-the-standard-wpf-tab-control and put this code inside my method:

void mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {       
        //do work when tab is changed
    }
}

After doing that the first problem had been solved, but then when I ran the application and tried to change of tab, an error was raised:

Dispatcher processing has been suspended, but messages are still being processed

Visual Studio points to the first line of code inside of if (e.Source is TabControl) { //here }

But I found this article selectionchanged-event-firing-exceptions-for-unknown-reasons and I could solve that problem writing some code as below:

void mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {       
        if (this.IsLoaded)
        {
            //do work when tab is changed
        }
    }
}

But right now I am having another problem which I havent been able to solve:

The event is firing twice! And another weird thing is that only the first time I try to change of selected tab the event raises twice but the selected tab is still the same

I hope someone can help me, thank you in advance.

like image 832
Dante Avatar asked Jun 13 '12 20:06

Dante


1 Answers

I think I need to take a rest, since my problem is really silly:

Turns out that instead of TabControl I should have used TabItem since it is the control I am interesting in.

So, my code has to be as below:

 void mainTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.Source is TabItem)
        {       
            if (this.IsLoaded)
            {
                //do work when tab is changed
            }
        }
    }
like image 104
Dante Avatar answered Oct 13 '22 07:10

Dante