【问题标题】:How to prevent TabControl from switching tabs when Button is pressed?如何防止 TabControl 在按下 Button 时切换选项卡?
【发布时间】:2019-12-04 21:33:37
【问题描述】:

我有一个新的 WPF (.NET Framework 4.7.2) 应用程序,其 Window XAML 定义如下:

<Window x:Class="WpfApp5.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="200" Width="300">
    <Grid>
        <TabControl>
            <TabItem Header="Tab">
                <ToolBarTray>
                    <ToolBar>
                        <Button>Button</Button>
                    </ToolBar>
                </ToolBarTray>
            </TabItem>
            <TabItem Header="Tab">
                <ToolBarTray>
                    <ToolBar>
                        <Button>Button</Button>
                    </ToolBar>
                </ToolBarTray>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

以及背后的代码:

using System.Windows;

namespace WpfApp5
{
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
    }
}

现在按照以下步骤操作:

  1. 运行应用程序并切换到第二个选项卡
  2. 切换回第一个选项卡并按下按钮

这使得 TabControl 无明显原因切换到第二个选项卡,如下所示:

有人能告诉我为什么会发生这种情况以及如何解决它,这样它就不会在按下按钮时切换标签吗?

非常感谢!


相关链接:

  1. https://github.com/dotnet/wpf/issues/2278

【问题讨论】:

  • 这是.Net version 4.7.1引入的bug,我在.Net version 4.6.2测试过你的代码没有这个问题。

标签: c# wpf


【解决方案1】:

对我来说足够好的解决方案是在 TabControl 上设置 x:Name 并将 FocusManager.FocusedElement 设置为 TabControl 名称:

<Window x:Class="WpfApp5.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="200" Width="300"
        FocusManager.FocusedElement="{Binding ElementName=tabControl}">
    <Grid>
        <TabControl x:Name="tabControl">
            <TabItem Header="Tab">
                <ToolBarTray>
                    <ToolBar>
                        <Button>Button</Button>
                    </ToolBar>
                </ToolBarTray>
            </TabItem>
            <TabItem Header="Tab">
                <ToolBarTray>
                    <ToolBar>
                        <Button>Button</Button>
                    </ToolBar>
                </ToolBarTray>
            </TabItem>
        </TabControl>
    </Grid>
</Window>

仍然不知道为什么会发生这种情况,所以这不是一个完美的答案。

【讨论】:

    猜你喜欢
    • 2021-08-08
    • 1970-01-01
    • 2018-05-14
    • 1970-01-01
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    相关资源
    最近更新 更多