KeyDown阻止文本出现在TextBox [UWP]

时间:2018-06-14 15:28:07

标签: c# uwp uwp-xaml

我目前的UWP应用定位为10240:

<Page x:Class="App8.MainPage"
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
      <Grid>
           <ContentControl KeyDown="ContentControl_KeyDown">
              <TextBox  TextChanged="TextBox_TextChanged"/>
           </ContentControl>
    </Grid>
</Page>

namespace App8
{  
     public sealed partial class MainPage : Page
     {
            public MainPage() => InitializeComponent();
            private void ContentControl_KeyDown(object sender, KeyRoutedEventArgs e) => e.Handled = true;
            private void TextBox_TextChanged(object sender, TextChangedEventArgs e) => Debug.WriteLine("NEVER RUNNING CODE");        
     }    
}

当我在文本框中书写时,我想避免任何关键事件进入主屏幕。为了做到这一点,我在文本框的父元素中有KeyDown,我处理事件。但是如果我这样做,文本框就不会写任何内容。

我想结束进入Page的ContentControl中的任何关键事件,但允许文本框正常工作。有什么想法吗?

1 个答案:

答案 0 :(得分:1)

  

我希望结束进入Page的ContentControl中的任何关键事件,但允许文本框正常工作。有什么想法吗?

根据您的要求,您可以制作bool标志,以便在TextBox聚焦或不聚焦时告诉主屏幕一些事件。

private bool IsFocus;
private void MyTextBox_GettingFocus(UIElement sender, GettingFocusEventArgs args)
{
    IsFocus = true;
}

private void MyTextBox_LostFocus(object sender, RoutedEventArgs e)
{
    IsFocus = false;
}

<强>用法

public MainPage()
{
    this.InitializeComponent();
    Window.Current.Dispatcher.AcceleratorKeyActivated += Dispatcher_AcceleratorKeyActivated;
}

private void Dispatcher_AcceleratorKeyActivated(Windows.UI.Core.CoreDispatcher sender, Windows.UI.Core.AcceleratorKeyEventArgs args)
{
    if (IsFocus)
    {
        System.Diagnostics.Debug.WriteLine("Do  Not Fire Your Event ");
        return;
    }
    else
    {
        System.Diagnostics.Debug.WriteLine(" Fire Your Event ");
    }

}