2012-06-19 69 views
1

我在我的应用程序中使用WPF TabControl以在程序的不同区域/功能之间切换。WPF:禁用tabcontrol上的箭头键

虽然有一件事让我恼火。我隐藏了标签,因此我可以控制选定的选项卡,而不是用户。不过,用户仍然可以使用箭头键在标签之间切换。

我已经尝试使用KeyboardNavigation属性,但我无法得到这个工作。

这可以禁用吗?

回答

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

谢谢!我使用附加的属性解决方案来保留MVVM结构。它工作得很好! –