Home > DeveloperSection > Forums > WPF SelectedIndex set issue of TabControl in WPF
Andrew Deniel
Andrew Deniel

Total Post:29

Points:203
Posted on    July-18-2013 3:07 AM

 WPF WPF 
Ratings:


 1 Reply(s)
 2360  View(s)
Rate this:
Hi experts!

I have a TabControl with two items.

<TabControl x:Name="tab" SelectionChanged="TabControl_SelectionChanged">

    <TabItem Header="TabItem1">

    <Grid />

</TabItem>

<TabItem Header="TabItem2">

    <Grid />

</TabItem>

</TabControl>

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

    Debug.WriteLine("Selected Index: " + tab.SelectedIndex);

    if (tab.SelectedIndex == 1)

    {

        tab.SelectedIndex = 0;

    }

}

when click 2nd item, 1st item have focus and print below.

Selected Index: 1

Selected Index: 0

but retry clicking 2nd item, no output! SelectionChanged event do not fire.

what's wrong? Is there work around?

thanks in advance 



shreesh chandra shukla
shreesh chandra shukla

Total Post:105

Points:735
Posted on    July-18-2013 11:21 PM

Solution!

This is because you are changing the selectedIndex within the SelcetedIndexChanged event which will call itself in sycnhronous manner. Instead try to put it on UI dispatcher in an aysnchronous manner like this -

private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)

{

   Debug.WriteLine("Selected Index: " + tab.SelectedIndex);

   if (tab.SelectedIndex == 1)

   {

      Application.Current.Dispatcher.BeginInvoke

          ((Action)delegate { tab.SelectedIndex = 0; }, DispatcherPriority.Render, null);

   }

}

It will give you the desired output.


Don't want to miss updates? Please click the below button!

Follow MindStick