我想实现一个自定义命令来捕获一个文本框内的退格键手势,但我不知道如何。我写了一个测试程序,以了解发生了什么,但程序的行为相当混乱。基本上,我只需要能够在键盘焦点位于文本框中时通过wpf命令处理Backspace键手势,并且不会中断文本框中Backspace键的正常行为。下面是主窗口中的XAML和相应的代码隐藏,太(注意,我创建了第二个命令回车键,只需比较其行为即退格键):路由命令问题
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<TextBox Margin="44,54,44,128"
Name="textBox1" />
</Grid>
</Window>
而这里的相应的代码隐藏:
using System.Windows;
using System.Windows.Input;
namespace WpfApplication1
{
/// <summary>
/// Interaction logic for EntryListView.xaml
/// </summary>
public partial class Window1 : Window
{
public static RoutedCommand EnterCommand = new RoutedCommand();
public static RoutedCommand BackspaceCommand = new RoutedCommand();
public Window1()
{
InitializeComponent();
CommandBinding cb1 = new CommandBinding(EnterCommand, EnterExecuted, EnterCanExecute);
CommandBinding cb2 = new CommandBinding(BackspaceCommand, BackspaceExecuted, BackspaceCanExecute);
this.CommandBindings.Add(cb1);
this.CommandBindings.Add(cb2);
KeyGesture kg1 = new KeyGesture(Key.Enter);
KeyGesture kg2 = new KeyGesture(Key.Back);
InputBinding ib1 = new InputBinding(EnterCommand, kg1);
InputBinding ib2 = new InputBinding(BackspaceCommand, kg2);
this.InputBindings.Add(ib1);
this.InputBindings.Add(ib2);
}
#region Command Handlers
private void EnterCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
MessageBox.Show("Inside EnterCanExecute Method.");
e.CanExecute = true;
}
private void EnterExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Inside EnterExecuted Method.");
e.Handled = true;
}
private void BackspaceCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
MessageBox.Show("Inside BackspaceCanExecute Method.");
e.Handled = true;
}
private void BackspaceExecuted(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("Inside BackspaceExecuted Method.");
e.Handled = true;
}
#endregion Command Handlers
}
}
任何帮助将非常感激。谢谢!
Andrew
我刚刚意识到我打算使用'e.CanExecute = true;'在名为BackspaceCanExecute的处理程序中,而不是'e.Handled = true;'。尽管如此,尽管如此,我仍然无法理解程序行为。 (1)EnterCanExecute被调用两次,用于调用EnterExecuted。 (2)仅当文本框没有键盘焦点时才调用BackspaceCanExecute。即使如此,BackspaceExecuted从未被调用过。 – Andrew 2010-05-08 20:09:40