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.
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With