WPF:禁用tabcontrol上的箭头键

时间:2012-06-19 07:50:14

标签: wpf xaml tabcontrol

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

但有一件事让我烦恼。我隐藏了标签,因此我可以控制selectedtab而不是用户。但是,用户仍然可以使用箭头键在标签之间切换。

我尝试过使用KeyboardNavigation属性,但我无法使用它。

可以禁用吗?

1 个答案:

答案 0 :(得分: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;
    }
}