我想在 WPF MVVM 应用程序中按 Enter 键而不是 Tab 键时移动到下一个控件。我怎样才能实现这个目标?
下面是我为此使用的附加属性。
首先,示例用法:
<TextBox Width="100"
Text="{Binding Name, Mode=TwoWay}"
UI:FocusAdvancement.AdvancesByEnterKey="True" />
(UI 是我定义以下内容的名称空间别名。)
附属财产:
public static class FocusAdvancement
{
public static bool GetAdvancesByEnterKey(DependencyObject obj)
{
return (bool)obj.GetValue(AdvancesByEnterKeyProperty);
}
public static void SetAdvancesByEnterKey(DependencyObject obj, bool value)
{
obj.SetValue(AdvancesByEnterKeyProperty, value);
}
public static readonly DependencyProperty AdvancesByEnterKeyProperty =
DependencyProperty.RegisterAttached("AdvancesByEnterKey", typeof(bool), typeof(FocusAdvancement),
new UIPropertyMetadata(OnAdvancesByEnterKeyPropertyChanged));
static void OnAdvancesByEnterKeyPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var element = d as UIElement;
if(element == null) return;
if ((bool)e.NewValue) element.KeyDown += Keydown;
else element.KeyDown -= Keydown;
}
static void Keydown(object sender, KeyEventArgs e)
{
if(!e.Key.Equals(Key.Enter)) return;
var element = sender as UIElement;
if(element != null) element.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
}
}
您还说了“而不是制表符”,所以我想知道您是否想禁止以通常的方式使用制表符。我建议不要这样做,因为这是一个常见的、众所周知的范例,但如果是这样的话,你可以添加一个PreviewKeyDown
附加属性中的处理程序,检查 Tab 键,然后设置Handled = true
对于事件参数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)