簡體   English   中英

WPF:按下回車按鈕時在搜索字段中執行命令綁定

[英]WPF: Execute a Command Binding in a search field when pressing the enter button

我的 WPF 應用程序中有一個搜索字段,其中包含一個包含命令綁定的搜索按鈕。 這很好用,但是當在鍵盤上按 Enter 時,我如何為文本字段使用相同的命令綁定? 我看到的例子都是使用帶有 KeyDown 事件處理程序的代碼。 有沒有一種聰明的方法可以只使用 xaml 和命令綁定來完成這項工作?

您可以使用按鈕的 IsDefault 屬性:

    <Button Command="SearchCommand" IsDefault="{Binding ElementName=SearchTextBox,
                                               Path=IsKeyboardFocused}">
         Search!
   </Button>

接受的答案僅在您已經有一個綁定到命令的按鈕時才有效。

要避免此限制,請使用 TextBox.InputBindings:

<TextBox.InputBindings>
    <KeyBinding Key="Enter" Command="{Binding Path=MyCommand}"></KeyBinding>
</TextBox.InputBindings>

Prism參考實現包含您所追求的實現。

基本步驟是:

  • 創建一個靜態類 EnterKey
  • 在 EnterKey 上注冊了 ICommand 類型的附加屬性“Command”
  • 在 EnterKey 上注冊了 EnterKeyCommandBehavior 類型的附加屬性“EnterKeyCommandBehavior”
  • 當“Command”的值更改時,將“EnterKeyCommandBehavior”作為 EnterKeyCommandBehavior 的新實例附加到控件,並將 ICommand 分配給行為的 Command 屬性。
    • 如果行為已附加,則使用現有實例
  • EnterKeyCommandBehavior 在構造函數中接受 UIElement 並附加到 PreviewKeyDown(或 KeyDown,如果您想保持 Silverlight 兼容)。
  • 在事件處理程序中,如果鍵為 Enter,則執行 ICommand(如果 CanExecute 為 true)。

這使您可以使用如下行為:

<TextBox prefix:EnterKey.Command="{Binding Path=SearchCommand}" />
<TextBox Text="{Binding SerachString, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Command="{Binding SearchCommand}" Key="Enter" />
    </TextBox.InputBindings>
</TextBox>

這應該可以正常工作。 100%

我已經嘗試了 Greg Samson 的 TextBox.Inputs 解決方案,但收到一個錯誤,說我只能通過依賴屬性綁定到 textinputs。 最后,我找到了下一個解決方案。

創建一個名為 CommandReference 的類,如下所示:

public class CommandReference : Freezable, ICommand
{
    public CommandReference()
    {
        //
    }

    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(CommandReference), new PropertyMetadata(new PropertyChangedCallback(OnCommandChanged)));

    public ICommand Command
    {
        get { return (ICommand)GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        if (Command != null)
            return Command.CanExecute(parameter);
        return false;
    }

    public void Execute(object parameter)
    {
        Command.Execute(parameter);
    }

    public event EventHandler CanExecuteChanged;

    private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        CommandReference commandReference = d as CommandReference;
        ICommand oldCommand = e.OldValue as ICommand;
        ICommand newCommand = e.NewValue as ICommand;

        if (oldCommand != null)
        {
            oldCommand.CanExecuteChanged -= commandReference.CanExecuteChanged;
        }
        if (newCommand != null)
        {
            newCommand.CanExecuteChanged += commandReference.CanExecuteChanged;
        }
    }

    #endregion

    #region Freezable

    protected override Freezable CreateInstanceCore()
    {
        throw new NotImplementedException();
    }

    #endregion
}

在 Xaml 中,將此添加到 UserControl 資源中:

<UserControl.Resources>
    <Base:CommandReference x:Key="SearchCommandRef" Command="{Binding Path = SomeCommand}"/>

實際的 TextBox 如下所示:

 <TextBox Text="{Binding Path=SomeText}">
                    <TextBox.InputBindings>
                        <KeyBinding Command="{StaticResource SearchCommandRef}" Key="Enter"/>
                    </TextBox.InputBindings>
                </TextBox>

我不記得我從哪里得到這個代碼,但是這個站點也解釋了它;

http://www.netframeworkdev.com/windows-presentation-foundation-wpf/invoke-a-command-with-enter-key-after-typing-in-a-textbox-21909.shtml

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM