[英]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參考實現包含您所追求的實現。
基本步驟是:
這使您可以使用如下行為:
<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>
我不記得我從哪里得到這個代碼,但是這個站點也解釋了它;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.