【发布时间】:2010-05-10 02:50:58
【问题描述】:
我想实现一个自定义命令来捕获文本框内的退格键手势,但我不知道如何。我编写了一个测试程序以了解发生了什么,但程序的行为相当混乱。基本上,我只需要能够在键盘焦点位于文本框中时通过 wpf 命令处理 Backspace 键手势,并且不会破坏文本框中 Backspace 键的正常行为。这是主窗口的 xaml 和相应的代码隐藏(请注意,我为 Enter 键创建了第二个命令,只是为了将其行为与 Backspace 键的行为进行比较):
<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
}
}
任何帮助将不胜感激。谢谢!
安德鲁
【问题讨论】:
-
我刚刚意识到我的意思是使用'e.CanExecute = true;'在名为 BackspaceCanExecute 的处理程序中,而不是 'e.Handled = true;'。但是,即使进行了这种更正,我仍然无法理解程序的行为。 (1) EnterCanExecute 被调用两次,每次调用 EnterExecuted。 (2) BackspaceCanExecute 仅在文本框没有键盘焦点时调用。即便如此,BackspaceExecuted 也永远不会被调用。