我以mvvm方式启动了WPF应用程序。主窗口包含一个用于浏览不同页面的框架控件。为此,我现在使用一个简单的NavigationService:

public class NavigationService : INavigationService
{

   private Frame _mainFrame;


    #region INavigationService Member

    public event NavigatingCancelEventHandler Navigating;

    public void NavigateTo(Uri uri)
    {
        if(EnsureMainFrame())
        {
            _mainFrame.Navigate(uri);
        }
    }

    public void GoBack()
    {
        if(EnsureMainFrame() && _mainFrame.CanGoBack)
        {
            _mainFrame.GoBack();
        }
    }

    #endregion

    private bool EnsureMainFrame()
    {
        if(_mainFrame != null)
        {
            return true;
        }

        var mainWindow = (System.Windows.Application.Current.MainWindow as MainWindow);
        if(mainWindow != null)
        {
            _mainFrame = mainWindow.NavigationFrame;
            if(_mainFrame != null)
            {
                // Could be null if the app runs inside a design tool
                _mainFrame.Navigating += (s, e) =>
                                             {
                                                 if (Navigating != null)
                                                 {
                                                     Navigating(s, e);
                                                 }
                                             };
                return true;
            }
        }
        return false;
    }

}


在Page1上,按下按钮即可使用NavigationService强制导航到Page2。
在Page2上有一个TextBox。如果TextBox聚焦,则可以使用ALT +左箭头键导航回到Page1。如何禁用此行为?

我尝试在框架控件和TextBox控件中设置KeyboardNavigation.DirectionalNavigation =“ None”均未成功。

最佳答案

将以下事件处理程序添加到文本框中以禁用alt +左​​导航:

private void textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
    if ((Keyboard.IsKeyDown(Key.LeftAlt) || Keyboard.IsKeyDown(Key.RightAlt))
        && (Keyboard.IsKeyDown(Key.Left)))
    {
         e.Handled = true;
    }
}


XAML

<TextBox ... KeyDown="textBox1_PreviewKeyDown" />


编辑:更改为PreviewKeyDown为了捕获箭头键事件

关于c# - 如何禁用Alt +箭头键框架导航?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11230333/

10-17 00:23