3

我正在使用 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,它会起作用,但我想使用一个按钮。我怎样才能做到这一点?

4

2 回答 2

1

This works:

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)
        {
        }
    }
}

Use the NiceButton instead of your Button in the XAML by including the xmlns of your namespace.

于 2012-11-24T07:00:39.020 回答
0

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

ButtonBase(Button 的基类)处理 KeyUp,以便它可以检查空格键或 Enter 键……当 ButtonBase 覆盖虚拟方法 OnKeyUp 时,就完成了对事件的处理。

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

于 2012-09-12T13:44:48.813 回答