【问题标题】:Determining the Enter key is pressed in a TextBox确定在 TextBox 中按下 Enter 键
【发布时间】:2010-07-20 22:58:52
【问题描述】:

考虑 Win Phone 7 中的 XAML 文本框。

  <TextBox x:Name="UserNumber"   />

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

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

  • 是特定于 TextBox 的事件,还是系统键盘事件?
  • 是否需要在每次按键时检查Enter?即类似于 ASCII 13?
  • 编写此要求的最佳方法是什么?

【问题讨论】:

    标签: silverlight xaml windows-phone-7


    【解决方案1】:

    文本框中的直接方法是

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

    【讨论】:

    • 我觉得自己很傻,但我也想不出该如何处理。感谢您的帮助。
    【解决方案2】:

    您将寻求实现特定于该文本框的 KeyDown 事件,并检查 KeyEventArgs 中实际按下的键(如果它与 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
        }
    }
    

    请注意,在 WP7 模拟器的 Beta 版中,虽然使用软件屏幕键盘可以正确检测 Enter 键,但如果您使用的是硬件键盘(通过按 Pause/Break 激活),则 Enter 键似乎以 Key.Unknown 的形式出现 - 或者至少,它是在我的计算机上这样做的......

    【讨论】:

      【解决方案3】:

      如果您不想在 XAML 的代码隐藏文件中添加任何代码并从 MVVM 体系结构角度保持设计干净,则可以使用以下方法。在您的 XAML 中定义您的绑定命令,如下所示:

       <TextBox 
      Text="{Binding Text}" 
      custom:KeyUp.Command="{Binding Path=DataContext.DoCommand, ElementName=root}" />
      

      在哪里KeyUp类:

      使用 System.Windows;
      使用 System.Windows.Controls;
      使用 System.Windows.Input;
      
      命名空间 PhoneGuitarTab.Controls
      {
          公共静态类 KeyUp
          {
              私有静态只读 DependencyProperty KeyUpCommandBehaviorProperty = DependencyProperty.RegisterAttached(
                  "KeyUpCommandBehavior",
                  类型(文本框命令行为),
                  typeof(KeyUp),
                  空值);
      
      
              ///
              /// 在 KeyUp 事件上执行的命令。
              ///
              公共静态只读 DependencyProperty CommandProperty = DependencyProperty.RegisterAttached(
                  “命令”,
                  类型(ICommand),
                  typeof(KeyUp),
                  新的 PropertyMetadata(OnSetCommandCallback));
      
              ///
              /// 在命令执行时提供的命令参数。
              ///
              公共静态只读 DependencyProperty CommandParameterProperty = DependencyProperty.RegisterAttached(
                  "命令参数",
                  类型(对象),
                  typeof(KeyUp),
                  新的 PropertyMetadata(OnSetCommandParameterCallback));
      
      
              ///
              /// 设置在 KeyUp 事件上执行。
              ///
              /// 附加命令的文本框依赖对象
              /// 附加命令
              [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "仅适用于 buttonbase")]
              public static void SetCommand(TextBox textBox, ICommand command)
              {
                  textBox.SetValue(CommandProperty, 命令);
              }
      
              ///
              /// 检索附加到 .
              ///
              /// 包含命令依赖属性的文本框
              /// 附加命令的值
              [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "仅适用于 buttonbase")]
              公共静态 ICommand GetCommand(文本框文本框)
              {
                  返回 textBox.GetValue(CommandProperty) 作为 ICommand;
              }
      
              ///
              /// 设置提供的 CommandParameter 附加属性的值。
              ///
              /// 附加命令参数的文本框
              /// 要附加的参数值
              [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "仅适用于 buttonbase")]
              public static void SetCommandParameter(TextBox textBox, object parameter)
              {
                  textBox.SetValue(CommandParameterProperty, 参数);
              }
      
              ///
              /// 获取提供的CommandParameter附加属性中的值
              ///
              /// 具有命令参数的文本框
              /// 属性值
              [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "仅适用于 buttonbase")]
              公共静态对象 GetCommandParameter(TextBox textBox)
              {
                  返回 textBox.GetValue(CommandParameterProperty);
              }
      
              私有静态无效 OnSetCommandCallback(DependencyObject 依赖对象,DependencyPropertyChangedEventArgs e)
              {
                  文本框文本框 = 依赖对象作为文本框;
                  如果(文本框!= null)
                  {
                      TextBoxCommandBehavior 行为 = GetOrCreateBehavior(textBox);
                      行为.Command = e.NewValue 作为 ICommand;
                  }
              }
      
              私有静态无效 OnSetCommandParameterCallback(DependencyObject 依赖对象,DependencyPropertyChangedEventArgs e)
              {
                  文本框文本框 = 依赖对象作为文本框;
                  如果(文本框!= null)
                  {
                      TextBoxCommandBehavior 行为 = GetOrCreateBehavior(textBox);
                      行为.CommandParameter = e.NewValue;
                  }
              }
      
              私有静态 TextBoxCommandBehavior GetOrCreateBehavior(文本框文本框)
              {
                  TextBoxCommandBehavior 行为 = textBox.GetValue(KeyUpCommandBehaviorProperty) as TextBoxCommandBehavior;
                  如果(行为 == 空)
                  {
                      行为 = 新文本框命令行为(文本框);
                      textBox.SetValue(KeyUpCommandBehaviorProperty, 行为);
                  }
      
                  返回行为;
              }
          }
      }

      该课程使用额外的,所以我也提供它们。 TextBoxCommandBehavior 类:

      使用系统;
      使用 System.Windows.Controls;
      使用 System.Windows.Input;
      
      命名空间 PhoneGuitarTab.Controls
      {
          公共类 TextBoxCommandBehavior : CommandBehaviorBase
          {
              公共文本框命令行为(文本框文本框对象)
                  :基础(文本框对象)
              {
                  textBoxObject.KeyUp += (s, e) =>
                                             {
                                                 字符串输入 = (s as TextBox).Text;
                                                 //TODO 在这里验证用户输入
                                                 **//ENTER 被按下!**
                                                 if ((e.Key == Key.Enter)
                                                     && (!String.IsNullOrEmpty(input)))
                                                 {
                                                     this.CommandParameter = 输入;
                                                     执行命令();
                                                 }
                                             };
      
              }
          }
      }

      CommandBehaviorBase 类:

      使用系统;
      使用 System.Windows.Controls;
      使用 System.Windows.Input;
      
      命名空间 PhoneGuitarTab.Controls
      {
          ///
          /// 处理将 a 连接到命令的基本行为。
          ///
          /// 目标对象必须从 Control 派生
          ///
          /// CommandBehaviorBase 可用于提供类似于 .
          ///
          公共类 CommandBehaviorBase
                      其中 T :控制
          {
              私有 ICommand 命令;
              私有对象命令参数;
              私有只读弱引用目标对象;
              私有只读 EventHandler commandCanExecuteChangedHandler;
      
      
              ///
              /// 指定目标对象的构造函数。
              ///
              /// 行为附加到的目标对象。
              公共命令行为基础(T 目标对象)
              {
                  this.targetObject = new WeakReference(targetObject);
                  this.commandCanExecuteChangedHandler = new EventHandler(this.CommandCanExecuteChanged);
              }
      
              ///
              /// 对应的要执行和监控的命令
              ///
              公共 ICommand 命令
              {
                  获取{返回命令; }
                  放
                  {
                      if (this.command != null)
                      {
                          this.command.CanExecuteChanged -= this.commandCanExecuteChangedHandler;
                      }
      
                      this.command = 值;
                      if (this.command != null)
                      {
                          this.command.CanExecuteChanged += this.commandCanExecuteChangedHandler;
                          更新启用状态();
                      }
                  }
              }
      
              ///
              /// 执行期间提供命令的参数
              ///
              公共对象命令参数
              {
                  获取 { 返回 this.commandParameter; }
                  放
                  {
                      if (this.commandParameter != value)
                      {
                          this.commandParameter = 值;
                          this.UpdateEnabledState();
                      }
                  }
              }
      
              ///
              /// 附加此行为的对象。
              ///
              受保护的 T 目标对象
              {
                  得到
                  {
                      返回 targetObject.Target 作为 T;
                  }
              }
      
      
              ///
              /// 根据命令的执行能力更新目标对象的 IsEnabled 属性。
              ///
              受保护的虚拟 void UpdateEnabledState()
              {
                  如果(目标对象 == 空)
                  {
                      this.Command = null;
                      this.CommandParameter = null;
                  }
                  否则如果(this.Command!= null)
                  {
                      TargetObject.IsEnabled = this.Command.CanExecute(this.CommandParameter);
                  }
              }
      
              私人无效CommandCanExecuteChanged(对象发送者,EventArgs e)
              {
                  this.UpdateEnabledState();
              }
      
              ///
              /// 执行命令,如果已设置,提供
              ///
              受保护的虚拟 void ExecuteCommand()
              {
                  如果(this.Command!= null)
                  {
                      this.Command.Execute(this.CommandParameter);
                  }
              }
          }
      }

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

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

        • 谢谢,我正在寻找一种方法让输入键在模拟器中工作。
        【解决方案5】:

        禁用键盘

        遇到了同样的问题;上面的例子只给出了关于 如何捕获键盘按下事件(它回答了问题),但是 禁用键盘,单击或输入,我只是将焦点设置为另一个 完全控制。

        这将导致禁用键盘。

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-20
          • 1970-01-01
          • 2023-04-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多