WPF SelectedIndex set issue of TabControl

大憨熊 提交于 2021-01-28 02:42:32

问题


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?


回答1:


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.




回答2:


If you click the tab that is already selected, there is no selection change now is there?
So the SelectionChanged event won't fire.

You would have to hook an event handler on the Click event of the Header of the TabItem



来源:https://stackoverflow.com/questions/7786300/wpf-selectedindex-set-issue-of-tabcontrol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!