如何在选项卡控件的空白区域捕获鼠标右键单击?

How to capture RightMouse Click in empty area of tab control?

我有一个普通的 C# 选项卡控件。当用户 right-clicks 在 right-most 选项卡 header 右侧的空白区域(选项卡 header 区域中不是选项卡的任何位置时,我想执行一个功能也可以)。

我考虑过在空白区域放置一个隐藏按钮,但它没有填充 space,是一种非常 hard-coded 的方法。

我也考虑过在空白区域创建一个隐藏选项卡,但它也不会完全填充空白区域 space 并且所需的 header 宽度取决于其他选项卡的数量展示;此外,用户可能会不小心单击它并离开当前选项卡,这不太好,因为选项卡更改时会自动发生。

有没有优雅的方法可以在空白区域捕获一个right-click?

我最终通过使用事件处理程序设置样式来做到这一点:

<Style x:Key="{dxt:DXTabControlInternalThemeKey ResourceKey=PanelContainerTopLayoutStyle, IsThemeIndependent=True}" TargetType="{x:Type dx:TabPanelContainer}" BasedOn="{StaticResource {dxt:DXTabControlInternalThemeKey ResourceKey=PanelContainerTopLayoutStyle}}">
        <EventSetter Event="PreviewMouseRightButtonDown" Handler="DXTabControl_PreviewMouseRightButtonDown"/>
        <Setter Property="Background" Value="Transparent"/>
    </Style>

然后我在事件处理程序中查看是否有这样的父对象:

    private void tabControl_PreviewMouseRightButtonDown(object sender, MouseButtonEventArgs e) {
        DXTabItem parentObject = DevExpress.Xpf.Core.Native.LayoutHelper.FindParentObject<DXTabItem>(e.OriginalSource as DependencyObject);

        // If the click happened over an empty area (i.e., no parent object was found), then toggle the admin button
        if (parentObject == null) {
            if (tabItem_Admin.Visibility == System.Windows.Visibility.Visible)
                tabItem_Admin.Visibility = System.Windows.Visibility.Collapsed;
            else
                tabItem_Admin.Visibility = System.Windows.Visibility.Visible;
        }
    }

此解决方案使用 DevExpress 库,由优秀的 DevExpress 支持团队提供!