首页 > 解决方案 > KeyDown 防止文本出现在 TextBox [UWP] 中

问题描述

我有针对 10240 的当前 UWP 应用程序:

<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,并处理该事件。但如果我这样做,文本框不会写任何东西。

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

标签: c#uwpuwp-xaml

解决方案


我想结束 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 ");
    }

}

推荐阅读