我想實現一個自定義命令來捕獲一個文本框內的退格鍵手勢,但我不知道如何。我寫了一個測試程序,以瞭解發生了什麼,但程序的行爲相當混亂。基本上,我只需要能夠在鍵盤焦點位於文本框中時通過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