【问题标题】:Bind Return key press to text box only while focused仅在聚焦时将 Return 键按下绑定到文本框
【发布时间】:2018-02-09 15:54:29
【问题描述】:

我想为TextBox 添加一个键绑定,这样当我按下 ENTER 键时,就会触发相应的命令,但我只希望在TextBox 具有专注于它。

以下代码添加了绑定,但只要按下 Return 键就会触发,无论焦点在窗口中的哪个位置。是否可以将键绑定限制为仅当 TextBox 具有焦点时?

<TextBox Text="{Binding SearchBoxNumber, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Key="Return" Command="{Binding SearchCommand}" />
    </TextBox.InputBindings>
</TextBox>

【问题讨论】:

    标签: wpf xaml key-bindings


    【解决方案1】:

    这是默认行为。如果我将以下两个TextBoxes 放在StackPanel 中,将键盘焦点放在第二个并按ENTER,则该命令不会触发。

    <StackPanel>
        <TextBox Text="{Binding SearchBoxNumber, UpdateSourceTrigger=PropertyChanged}">
            <TextBox.InputBindings>
                <KeyBinding Key="Return" Command="{Binding SearchCommand}" />
            </TextBox.InputBindings>
        </TextBox>
    
        <TextBox />
    </StackPanel>
    

    【讨论】:

      【解决方案2】:

      您可以向SearchCommand.CanExecute 添加条件,以便在焦点不在TextBox 时返回false。不幸的是,IsFocusedIsKeyboardFocusedIsKeyboardFocusWithin 都是只读 DP,即使您将 Mode 设置为 OneWayToSource,您也无法从标记 (XAML) 绑定到它们。为此,您可以创建自己的源自TextBox 的控件。

      public class FocusAwareTextBox : TextBox
      {
          protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e)
          {
              if (e.OldValue != e.NewValue && e.NewValue != null)
              {
                  HasFocus = (bool)e.NewValue;
              }
      
              base.OnIsKeyboardFocusWithinChanged(e);
          }
      
          public bool HasFocus
          {
              get { return (bool)GetValue(HasFocusProperty); }
              set { SetValue(HasFocusProperty, value); }
          }
      
          public static readonly DependencyProperty HasFocusProperty =
              DependencyProperty.Register(
                  nameof(HasFocus),
                  typeof(bool),
                  typeof(FocusAwareTextBox),
                  new PropertyMetadata(false));
      }
      

      然后,您将 HasFocus DP 绑定到 ViewModel 中的新 bool 属性,并在您的 SearchCommand.CanExecute 中添加对该 bool 属性的检查。

      另一种解决方案是处理KeyDown 事件并从那里调用命令。请注意,您必须使用 Behavior 来保持 MVVM 模式。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-24
        • 1970-01-01
        • 2010-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多