【问题标题】:Capture Enter & Spacebar on Windows 8 Metro-style c# Application在 Windows 8 Metro 风格 c# 应用程序上捕获 Enter 和空格键
【发布时间】:2012-09-12 13:25:08
【问题描述】:

我正在使用 C# 和 XAML,在 Windows 8 上开发 Metro 风格的应用程序。我想在 keyup 事件上捕获 enter 按钮,但它适用于除 enter 和空格键之外的所有键盘按钮。我的代码

XAML

<Button x:Name="btnName" KeyUp="KeyboardKey_Pressed">
</Button>

C#源代码

 public void KeyboardKey_Pressed(object sender, KeyRoutedEventArgs e)
 {        
     if (e.Key == Windows.System.VirtualKey.Enter)
            ......        
 }

我知道如果我使用 TextBox 而不是 Button,它会起作用,但我想使用一个按钮。我该怎么做?

【问题讨论】:

  • 在 TextBox 上使用 Button 不是打破常规 UI 约定吗?

标签: .net xaml windows-8 windows-runtime


【解决方案1】:

这行得通:

using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Input;


namespace YourNamespace
{
    public sealed class NiceButton: Button
    {
        public NiceButton()
            : base()
        {

        }
        protected override void OnKeyUp(KeyRoutedEventArgs e)
        {
        }
    }
}

通过包含命名空间的 xmlns,在 XAML 中使用 NiceButton 而不是 Button。

【讨论】:

    【解决方案2】:

    根据http://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh868246.aspx,该:

    ButtonBase(Button 的基类)处理 KeyUp 以便它可以 检查空格键或回车键...此事件处理是 当 ButtonBase 覆盖虚拟方法 OnKeyUp 时完成。

    因此,为防止它捕获空格键或 Enter 键,请创建一个派生自 Button 的新按钮类,覆盖 OnKeyUp 并且不要调用基类实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-25
      • 1970-01-01
      相关资源
      最近更新 更多