我有带有文本框和按钮的应用程序。当我在文本框中单击ENTER时,我想将焦点设置在按钮上(使用遍历),但是当按钮获得焦点时,执行命令。当按钮获得焦点时,我不想执行命令。这是我的代码:
View1.xaml
<TextBox PreviewKeyDown="UIElement_OnPreviewKeyDown"/>
View1.xaml.cs
private void UIElement_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Return) return;
TraversalRequest tRequest = new TraversalRequest(FocusNavigationDirection.Next);
UIElement keyboardFocus = Keyboard.FocusedElement as UIElement;
keyboardFocus?.MoveFocus(tRequest);
}
View2.xaml
<Button Content="Testbutton" Command="{Binding TestCommand}"/>
View2Vm
class View2Vm : BaseVm
{
public RelayCommand TestCommand { get; set; }
public View2Vm()
=> TestCommand = new RelayCommand(x => { MessageBox.Show("Message"); });
}
如何在不执行命令的情况下将焦点设置在按钮上?谢谢
答案 0 :(得分:0)
KeyDown事件仍处于启用状态。解决方法是:
private void UIElement_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key != Key.Return) return;
TraversalRequest tRequest = new TraversalRequest(FocusNavigationDirection.Next);
UIElement keyboardFocus = Keyboard.FocusedElement as UIElement;
keyboardFocus?.MoveFocus(tRequest);
e.Handled = true;
}