1
我在我的應用程序中使用WPF TabControl以在程序的不同區域/功能之間切換。WPF:禁用tabcontrol上的箭頭鍵
雖然有一件事讓我惱火。我隱藏了標籤,因此我可以控制選定的選項卡,而不是用戶。不過,用戶仍然可以使用箭頭鍵在標籤之間切換。
我已經嘗試使用KeyboardNavigation屬性,但我無法得到這個工作。
這可以禁用嗎?
我在我的應用程序中使用WPF TabControl以在程序的不同區域/功能之間切換。WPF:禁用tabcontrol上的箭頭鍵
雖然有一件事讓我惱火。我隱藏了標籤,因此我可以控制選定的選項卡,而不是用戶。不過,用戶仍然可以使用箭頭鍵在標籤之間切換。
我已經嘗試使用KeyboardNavigation屬性,但我無法得到這個工作。
這可以禁用嗎?
您可以掛鉤到此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;
}
}
謝謝!我使用附加的屬性解決方案來保留MVVM結構。它工作得很好! –