WPF TabControl的SelectedIndex设置问题

发布于 12-10 18:23 字数 688 浏览 1 评论 0原文

我有一个包含两个项目的 TabControl。

<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;
    }
}

当单击第二项时,第一项具有焦点并在下面打印。

Selected Index: 1
Selected Index: 0

但重试单击第二项,没有输出! SelectionChanged 事件不会触发。

怎么了? 有解决办法吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情话已封尘2024-12-17 18:23:27

这是因为您正在 SelcetedIndexChanged 事件中更改 selectedIndex,该事件将以同步方式调用自身。相反,尝试以异步方式将其放在 UI 调度程序上,如下所示 -

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);
   }
}

它将为您提供所需的输出。

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.

澉约2024-12-17 18:23:27

如果您单击已选择的选项卡,现在没有选择更改,是吗?
因此 SelectionChanged 事件不会触发。

您必须在 TabItem 标题的 Click 事件上挂接一个事件处理程序

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文