2

我在我的应用程序中使用 WPF TabControl 以便在程序的不同区域/功能之间切换。

不过有一件事让我很恼火。我已经隐藏了选项卡,所以我可以控制选定的选项卡,而不是用户。但是,用户仍然可以使用箭头键在选项卡之间切换。

我曾尝试使用 KeyboardNavigation-attribute,但无法正常工作。

这可以禁用吗?

4

1 回答 1

3

您可以为此连接到 TabControl.PreviewKeyDown 事件。检查它是左箭头还是右箭头,并说你已经处理了它。

    private void TabControl_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Left || e.Key == Key.Right)
            e.Handled = true;
    }

如果您使用的是纯视图模型应用程序,则可以将上述内容作为附加属性应用。

XAMl 使用以下附加属性。

<TabControl local:TabControlAttached.IsLeftRightDisabled="True">
    <TabItem Header="test"/>
    <TabItem Header="test"/>
</TabControl>

TabControlAttached.cs

public class TabControlAttached : DependencyObject
{
    public static bool GetIsLeftRightDisabled(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsLeftRightDisabledProperty);
    }

    public static void SetIsLeftRightDisabled(DependencyObject obj, bool value)
    {
        obj.SetValue(IsLeftRightDisabledProperty, value);
    }

    // Using a DependencyProperty as the backing store for IsLeftRightDisabled.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty IsLeftRightDisabledProperty =
        DependencyProperty.RegisterAttached("IsLeftRightDisabled", typeof(bool), typeof(MainWindow), new UIPropertyMetadata(false, new PropertyChangedCallback((s, e) =>
        {
            // get a reference to the tab control.
            TabControl targetTabControl = s as TabControl;
            if (targetTabControl != null)
            {
                if ((bool)e.NewValue)
                {
                    // Need some events from it.
                    targetTabControl.PreviewKeyDown += new KeyEventHandler(targetTabControl_PreviewKeyDown);
                    targetTabControl.Unloaded += new RoutedEventHandler(targetTabControl_Unloaded);
                }
                else if ((bool)e.OldValue)
                {
                    targetTabControl.PreviewKeyDown -= new KeyEventHandler(targetTabControl_PreviewKeyDown);
                    targetTabControl.Unloaded -= new RoutedEventHandler(targetTabControl_Unloaded);
                }
            }
        })));

    static void targetTabControl_Unloaded(object sender, RoutedEventArgs e)
    {

        TabControl targetTabControl = sender as TabControl;
        targetTabControl.PreviewKeyDown -= new KeyEventHandler(targetTabControl_PreviewKeyDown);
        targetTabControl.Unloaded -= new RoutedEventHandler(targetTabControl_Unloaded);
    }

    static void targetTabControl_PreviewKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Left || e.Key == Key.Right)
            e.Handled = true;
    }
}
于 2012-06-19T08:07:47.863 回答