SelectedIndex is unchanging in tabcontrol - Dispatcher issue

366 Views Asked by At

Why, after I set SelectedIndex=0, do I subsequently (not in response) get the event handler invoked with SelectedIndex=4? I traced it down to an invocation of a Dispatcher, but I do not understand why.

Here's the plan: I have a page containting a tab control with assorted tabs. When I click on certain kinds of tabs, I want to switch out of this page to another page. The trouble is, when I return to this page, I'm getting looped back out to the other page again, and I can't figure out why.

Specifically, I set SelectedIndex=0, and then [External Code] changes SelectedIndex to 4, causing the page to be switched out again.

// In JobTreePage.xaml

<TabControl x:Name="mainTab"              
            ItemsSource="{Binding}"
            SelectionChanged="mainTab_SelectionChanged">

// in JobTreePage

private void mainTab_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
  e.Handled = true;
  if (!ready) return;
  var ee = this.TryFindResource("Title");
  TabItem x = mainTab.SelectedItem as TabItem;
  if (x == null) return;

  if (IsJobTab(x)) // index 4 is a job tab
  {
      if (ready ) // assuming the job selected is 1273.
      {
        ResetTab();
        //mainTab.SelectedItem = AddNew;
        mw.moldDataButton_Click(sender, e);
      }
    ready = true;

  }
}
public void ResetTab()
{
  ready = false;
  Application.Current.Dispatcher.BeginInvoke
     ((Action)delegate { mainTab.SelectedIndex = 0; }, DispatcherPriority.Send, null);

  //mainTab.SelectedIndex = 0; 
  ready = true; 
}

And in the MainWindow I have two buttons:

public void moldDataButton_Click(object sender, RoutedEventArgs e)
{
  CurrentPage = this.moldDataPage;
  moldDataPage.ActivateTab("Project");

  // the problem line.  problem arises after I click on the Customers button.
  Dispatcher.Invoke(new System.Action(() => { }), DispatcherPriority.ContextIdle, null);
  Slow_COM_Operation();
}

private void CustomersButton_Click(object sender, RoutedEventArgs e)
{
  this.jobTreePage.ResetTab();
  CurrentPage = this.jobTreePage;
}

So tracing the program from CustomersButton_Click(), in ResetTab, SelectedIndex == 0, but after that finishes we jump to mainTab_SelectionChanged and see that SelectedIndex == 4. I have no idea what is forcing SelectedIndex to 4.

Aside: Why do I have this dispatcher line? Because I'm attempting to send an asynchronous request via COM interop to get some other stuff happening without the dialog freezing. I don't know how to achieve the goal, but putting in the line at least gives me a page refresh.

0

There are 0 best solutions below