路由命令问题

时间:2010-05-08 19:13:00

标签: wpf command

我想实现一个自定义命令来捕获文本框中的Backspace键手势,但我不知道如何。我写了一个测试程序,以了解发生了什么,但程序的行为相当混乱。基本上,我只需要能够通过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
    }
}

非常感谢任何帮助。谢谢!

安德鲁

1 个答案:

答案 0 :(得分:0)

尝试将输入绑定和命令绑定添加到文本块而不是主窗口。

在XAML中:

<TextBox x:Name ="tb1"/>

在代码中

tb1.CommandBindings.Add(CB2);

...

tb1.InputBindings.Add(IB2);

我不确定原因,但是当您点击退格键时,文本块会阻止keydown事件冒泡到窗口。 (您可以通过在主窗口上向KeyDown事件添加处理程序来测试这一点。当您按Enter键时,处理程序将触发,但是当您按退格键时,事件处理程序不会触发)。由于RoutedCommands基于RoutedEvents,如this post by Josh Smith中所述,这意味着窗口上的命令永远不会触发。