在TextBox中按下确定Enter键

p.c*_*ell 40 silverlight xaml windows-phone-7

考虑Win Phone 7中的XAML TextBox.

  <TextBox x:Name="UserNumber"   />
Run Code Online (Sandbox Code Playgroud)

这里的目标是当用户按下Enter屏幕键盘上的按钮时,这将启动一些逻辑以刷新屏幕上的内容.

我想专门为此举办一个活动Enter.这可能吗?

  • 事件是特定于TextBox的,还是系统键盘事件?
  • 是否需要检查Enter每个按键?即一些模拟ASCII 13?
  • 编写此要求的最佳方法是什么?

替代文字

Mic*_*k N 71

在文本框中直接进行此操作是

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        Debug.WriteLine("Enter");
    }
}
Run Code Online (Sandbox Code Playgroud)


Hen*_*y C 13

您将要实现特定于该文本框的KeyDown事件,并检查KeyEventArgs是否按下了实际的Key(如果它与Key.Enter匹配,则执行某些操作)

<TextBox Name="Box" InputScope="Text" KeyDown="Box_KeyDown"></TextBox>

private void Box_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key.Equals(Key.Enter))
    {
        //Do something
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在WP7仿真器的Beta版本中,虽然使用软件屏幕键盘正确检测到Enter键,但如果您正在使用硬件键盘(通过按暂停/中断激活),则Enter键似乎来了通过Key.Unknown - 或者至少,它是在我的电脑上这样做的......


Ily*_*luk 9

如果您不想将任何代码添加到XAML的代码隐藏文件中并使您的设计从MVVM架构点清除,则可以使用以下方法.在您的XAML中,在绑定中定义您的命令,如下所示:

 <TextBox 
Text="{Binding Text}" 
custom:KeyUp.Command="{Binding Path=DataContext.DoCommand, ElementName=root}" />
Run Code Online (Sandbox Code Playgroud)

其中KeyUp类:

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace PhoneGuitarTab.Controls
{
    public static class KeyUp
    {
        private static readonly DependencyProperty KeyUpCommandBehaviorProperty = DependencyProperty.RegisterAttached(
            "KeyUpCommandBehavior",
            typeof(TextBoxCommandBehavior),
            typeof(KeyUp),
            null);


        /// 
        /// Command to execute on KeyUp event.
        /// 
        public static readonly DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
            "Command",
            typeof(ICommand),
            typeof(KeyUp),
            new PropertyMetadata(OnSetCommandCallback));

        /// 
        /// Command parameter to supply on command execution.
        /// 
        public static readonly DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached(
            "CommandParameter",
            typeof(object),
            typeof(KeyUp),
            new PropertyMetadata(OnSetCommandParameterCallback));


        /// 
        /// Sets the  to execute on the KeyUp event.
        /// 
        /// TextBox dependency object to attach command
        /// Command to attach
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
        public static void SetCommand(TextBox textBox, ICommand command)
        {
            textBox.SetValue(CommandProperty, command);
        }

        /// 
        /// Retrieves the  attached to the .
        /// 
        /// TextBox containing the Command dependency property
        /// The value of the command attached
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
        public static ICommand GetCommand(TextBox textBox)
        {
            return textBox.GetValue(CommandProperty) as ICommand;
        }

        /// 
        /// Sets the value for the CommandParameter attached property on the provided .
        /// 
        /// TextBox to attach CommandParameter
        /// Parameter value to attach
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
        public static void SetCommandParameter(TextBox textBox, object parameter)
        {
            textBox.SetValue(CommandParameterProperty, parameter);
        }

        /// 
        /// Gets the value in CommandParameter attached property on the provided 
        /// 
        /// TextBox that has the CommandParameter
        /// The value of the property
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "Only works for buttonbase")]
        public static object GetCommandParameter(TextBox textBox)
        {
            return textBox.GetValue(CommandParameterProperty);
        }

        private static void OnSetCommandCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = dependencyObject as TextBox;
            if (textBox != null)
            {
                TextBoxCommandBehavior behavior = GetOrCreateBehavior(textBox);
                behavior.Command = e.NewValue as ICommand;
            }
        }

        private static void OnSetCommandParameterCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            TextBox textBox = dependencyObject as TextBox;
            if (textBox != null)
            {
                TextBoxCommandBehavior behavior = GetOrCreateBehavior(textBox);
                behavior.CommandParameter = e.NewValue;
            }
        }

        private static TextBoxCommandBehavior GetOrCreateBehavior(TextBox textBox)
        {
            TextBoxCommandBehavior behavior = textBox.GetValue(KeyUpCommandBehaviorProperty) as TextBoxCommandBehavior;
            if (behavior == null)
            {
                behavior = new TextBoxCommandBehavior(textBox);
                textBox.SetValue(KeyUpCommandBehaviorProperty, behavior);
            }

            return behavior;
        }
    }
}

该课程使用其他课程,所以我也提供了.TextBoxCommandBehavior类:

using System;
using System.Windows.Controls;
using System.Windows.Input;

namespace PhoneGuitarTab.Controls
{
    public class TextBoxCommandBehavior : CommandBehaviorBase
    {
        public TextBoxCommandBehavior(TextBox textBoxObject)
            : base(textBoxObject)
        {
            textBoxObject.KeyUp += (s, e) =>
                                       {
                                           string input = (s as TextBox).Text;
                                           //TODO validate user input here
                                           **//ENTER IS PRESSED!**
                                           if ((e.Key == Key.Enter) 
                                               && (!String.IsNullOrEmpty(input)))
                                           {
                                               this.CommandParameter = input;
                                               ExecuteCommand();
                                           }
                                       };

        }
    }
}

CommandBehaviorBase类:

using System;
using System.Windows.Controls;
using System.Windows.Input;

namespace PhoneGuitarTab.Controls
{
    /// 
    /// Base behavior to handle connecting a  to a Command.
    /// 
    /// The target object must derive from Control
    /// 
    /// CommandBehaviorBase can be used to provide new behaviors similar to .
    /// 
    public class CommandBehaviorBase
                where T : Control
    {
        private ICommand command;
        private object commandParameter;
        private readonly WeakReference targetObject;
        private readonly EventHandler commandCanExecuteChangedHandler;


        /// 
        /// Constructor specifying the target object.
        /// 
        /// The target object the behavior is attached to.
        public CommandBehaviorBase(T targetObject)
        {
            this.targetObject = new WeakReference(targetObject);
            this.commandCanExecuteChangedHandler = new EventHandler(this.CommandCanExecuteChanged);
        }

        /// 
        /// Corresponding command to be execute and monitored for 
        /// 
        public ICommand Command
        {
            get { return command; }
            set
            {
                if (this.command != null)
                {
                    this.command.CanExecuteChanged -= this.commandCanExecuteChangedHandler;
                }

                this.command = value;
                if (this.command != null)
                {
                    this.command.CanExecuteChanged += this.commandCanExecuteChangedHandler;
                    UpdateEnabledState();
                }
            }
        }

        /// 
        /// The parameter to supply the command during execution
        /// 
        public object CommandParameter
        {
            get { return this.commandParameter; }
            set
            {
                if (this.commandParameter != value)
                {
                    this.commandParameter = value;
                    this.UpdateEnabledState();
                }
            }
        }

        /// 
        /// Object to which this behavior is attached.
        /// 
        protected T TargetObject
        {
            get
            {
                return targetObject.Target as T;
            }
        }


        /// 
        /// Updates the target object's IsEnabled property based on the commands ability to execute.
        /// 
        protected virtual void UpdateEnabledState()
        {
            if (TargetObject == null)
            {
                this.Command = null;
                this.CommandParameter = null;
            }
            else if (this.Command != null)
            {
                TargetObject.IsEnabled = this.Command.CanExecute(this.CommandParameter);
            }
        }

        private void CommandCanExecuteChanged(object sender, EventArgs e)
        {
            this.UpdateEnabledState();
        }

        /// 
        /// Executes the command, if it's set, providing the 
        /// 
        protected virtual void ExecuteCommand()
        {
            if (this.Command != null)
            {
                this.Command.Execute(this.CommandParameter);
            }
        }
    }
}

您可以在我的开源项目中找到工作示例(解决方案中的PhoneGuitarTab.Controls项目):http: //phoneguitartab.codeplex.com


San*_*ock 6

如果您使用的是模拟器,您也可以执行类似的操作来检测物理键盘上的回车键.

    private void textBox1_KeyUp(object sender, KeyEventArgs e) {
        var isEnterKey =
            e.Key == System.Windows.Input.Key.Enter ||
            e.PlatformKeyCode == 10;

        if (isEnterKey) {
            // ...
        }
    }
Run Code Online (Sandbox Code Playgroud)


小智 5

禁用键盘

面对同样的问题; 上面的示例仅提供有关如何捕获键盘按下事件(回答问题)的详细信息,但要禁用键盘,onclick或enter,我只需将焦点设置为另一个控件.

这将导致禁用键盘.

private void txtCodeText_KeyDown(object sender, KeyEventArgs e)
{
    if(e.Key.Equals(Key.Enter))
    {
        //setting the focus to different control
        btnTransmit.Focus();
    }
}
Run Code Online (Sandbox Code Playgroud)