57

如何在不使用代码隐藏的情况下处理 Keyboard.KeyDown 事件?我们正在尝试使用 MVVM 模式并避免在代码隐藏文件中编写事件处理程序。

4

8 回答 8

248

为了带来更新的答案,.net 4.0 框架允许您通过将 KeyBinding 命令绑定到视图模型中的命令来很好地做到这一点。

所以......如果你想听 Enter 键,你会做这样的事情:

<TextBox AcceptsReturn="False">
    <TextBox.InputBindings>
        <KeyBinding 
            Key="Enter" 
            Command="{Binding SearchCommand}" 
            CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />
    </TextBox.InputBindings>
</TextBox>
于 2011-08-17T00:54:24.963 回答
30

哇 - 好像有一千个答案,在这里我要添加另一个..

以“为什么我没有意识到这个额头拍”的方式,真正明显的事情是代码隐藏和ViewModel坐在同一个房间里可以这么说,所以没有理由为什么他们不被允许进行对话。

如果您考虑一下,XAML 已经与 ViewModel 的 API 紧密耦合,因此您不妨从后面的代码中对其进行依赖。

遵守或忽略的其他明显规则仍然适用(接口、空检查 <-- 特别是如果您使用 Blend...)

我总是在代码隐藏中创建一个属性,如下所示:

private ViewModelClass ViewModel { get { return DataContext as ViewModelClass; } }

这是客户端代码。空检查是为了帮助控制托管,就像在混合中一样。

void someEventHandler(object sender, KeyDownEventArgs e)
{
    if (ViewModel == null) return;
    /* ... */
    ViewModel.HandleKeyDown(e);
}

像你想要的那样在后面的代码中处理你的事件(UI 事件是以 UI 为中心的,所以没关系),然后在 ViewModelClass 上有一个可以响应该事件的方法。这些担忧仍然是分开的。

ViewModelClass
{
    public void HandleKeyDown(KeyEventArgs e) { /* ... */ }
}

所有这些其他附加属性和巫毒都非常酷,这些技术对其他一些事情真的很有用,但在这里你可能会得到一些更简单的东西......

于 2009-09-18T11:36:24.510 回答
8

我通过使用具有 3 个依赖属性的附加行为来做到这一点;一个是要执行的命令,一个是要传递给命令的参数,另一个是导致命令执行的键。这是代码:

public static class CreateKeyDownCommandBinding
{
    /// <summary>
    /// Command to execute.
    /// </summary>
    public static readonly DependencyProperty CommandProperty =
        DependencyProperty.RegisterAttached("Command",
        typeof(CommandModelBase),
        typeof(CreateKeyDownCommandBinding),
        new PropertyMetadata(new PropertyChangedCallback(OnCommandInvalidated)));

    /// <summary>
    /// Parameter to be passed to the command.
    /// </summary>
    public static readonly DependencyProperty ParameterProperty =
        DependencyProperty.RegisterAttached("Parameter",
        typeof(object),
        typeof(CreateKeyDownCommandBinding),
        new PropertyMetadata(new PropertyChangedCallback(OnParameterInvalidated)));

    /// <summary>
    /// The key to be used as a trigger to execute the command.
    /// </summary>
    public static readonly DependencyProperty KeyProperty =
        DependencyProperty.RegisterAttached("Key",
        typeof(Key),
        typeof(CreateKeyDownCommandBinding));

    /// <summary>
    /// Get the command to execute.
    /// </summary>
    /// <param name="sender"></param>
    /// <returns></returns>
    public static CommandModelBase GetCommand(DependencyObject sender)
    {
        return (CommandModelBase)sender.GetValue(CommandProperty);
    }

    /// <summary>
    /// Set the command to execute.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="command"></param>
    public static void SetCommand(DependencyObject sender, CommandModelBase command)
    {
        sender.SetValue(CommandProperty, command);
    }

    /// <summary>
    /// Get the parameter to pass to the command.
    /// </summary>
    /// <param name="sender"></param>
    /// <returns></returns>
    public static object GetParameter(DependencyObject sender)
    {
        return sender.GetValue(ParameterProperty);
    }

    /// <summary>
    /// Set the parameter to pass to the command.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="parameter"></param>
    public static void SetParameter(DependencyObject sender, object parameter)
    {
        sender.SetValue(ParameterProperty, parameter);
    }

    /// <summary>
    /// Get the key to trigger the command.
    /// </summary>
    /// <param name="sender"></param>
    /// <returns></returns>
    public static Key GetKey(DependencyObject sender)
    {
        return (Key)sender.GetValue(KeyProperty);
    }

    /// <summary>
    /// Set the key which triggers the command.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="key"></param>
    public static void SetKey(DependencyObject sender, Key key)
    {
        sender.SetValue(KeyProperty, key);
    }

    /// <summary>
    /// When the command property is being set attach a listener for the
    /// key down event.  When the command is being unset (when the
    /// UIElement is unloaded for instance) remove the listener.
    /// </summary>
    /// <param name="dependencyObject"></param>
    /// <param name="e"></param>
    static void OnCommandInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = (UIElement)dependencyObject;
        if (e.OldValue == null && e.NewValue != null)
        {
            element.AddHandler(UIElement.KeyDownEvent,
                new KeyEventHandler(OnKeyDown), true);
        }

        if (e.OldValue != null && e.NewValue == null)
        {
            element.RemoveHandler(UIElement.KeyDownEvent,
                new KeyEventHandler(OnKeyDown));
        }
    }

    /// <summary>
    /// When the parameter property is set update the command binding to
    /// include it.
    /// </summary>
    /// <param name="dependencyObject"></param>
    /// <param name="e"></param>
    static void OnParameterInvalidated(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
    {
        UIElement element = (UIElement)dependencyObject;
        element.CommandBindings.Clear();

        // Setup the binding
        CommandModelBase commandModel = e.NewValue as CommandModelBase;
        if (commandModel != null)
        {
            element.CommandBindings.Add(new CommandBinding(commandModel.Command,
            commandModel.OnExecute, commandModel.OnQueryEnabled));
        }
    }

    /// <summary>
    /// When the trigger key is pressed on the element, check whether
    /// the command should execute and then execute it.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    static void OnKeyDown(object sender, KeyEventArgs e)
    {
        UIElement element = sender as UIElement;
        Key triggerKey = (Key)element.GetValue(KeyProperty);

        if (e.Key != triggerKey)
        {
            return;
        }

        CommandModelBase cmdModel = (CommandModelBase)element.GetValue(CommandProperty);
        object parameter = element.GetValue(ParameterProperty);
        if (cmdModel.CanExecute(parameter))
        {
            cmdModel.Execute(parameter);
        }
        e.Handled = true;
    }
}

要从 xaml 使用它,您可以执行以下操作:

<TextBox framework:CreateKeyDownCommandBinding.Command="{Binding MyCommand}">
    <framework:CreateKeyDownCommandBinding.Key>Enter</framework:CreateKeyDownCommandBinding.Key>
</TextBox>

编辑: CommandModelBase 是我用于所有命令的基类。它基于 Dan Crevier 关于 MVVM 的文章(此处)中的 CommandModel 类。这是我与 CreateKeyDownCommandBinding 一起使用的略微修改版本的源代码:

public abstract class CommandModelBase : ICommand
    {
        RoutedCommand routedCommand_;

        /// <summary>
        /// Expose a command that can be bound to from XAML.
        /// </summary>
        public RoutedCommand Command
        {
            get { return routedCommand_; }
        }

        /// <summary>
        /// Initialise the command.
        /// </summary>
        public CommandModelBase()
        {
            routedCommand_ = new RoutedCommand();
        }

        /// <summary>
        /// Default implementation always allows the command to execute.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnQueryEnabled(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = CanExecute(e.Parameter);
            e.Handled = true;
        }

        /// <summary>
        /// Subclasses must provide the execution logic.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void OnExecute(object sender, ExecutedRoutedEventArgs e)
        {
            Execute(e.Parameter);
        }

        #region ICommand Members

        public virtual bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public abstract void Execute(object parameter);

        #endregion
    }

非常欢迎提出改进意见和建议。

于 2009-03-10T09:36:51.393 回答
8

有点晚了,但这里。

Microsoft 的 WPF 团队最近发布了他们的WPF MVVM Toolkit的早期版本 。在其中,您会找到一个名为 CommandReference 的类,它可以处理键绑定之类的事情。查看他们的 WPF MVVM 模板,了解它是如何工作的。

于 2009-05-27T21:20:14.010 回答
3

几个月前我研究了这个问题,我写了一个标记扩展来解决这个问题。它可以像常规绑定一样使用:

<Window.InputBindings>
    <KeyBinding Key="E" Modifiers="Control" Command="{input:CommandBinding EditCommand}"/>
</Window.InputBindings>

这个扩展的完整源代码可以在这里找到:

http://www.thomaslevesque.com/2009/03/17/wpf-using-inputbindings-with-the-mvvm-pattern/

请注意,这种解决方法可能不是很“干净”,因为它通过反射使用了一些私有类和字段......

于 2009-05-06T23:11:33.283 回答
3

类似于 karlipoppins 答案,但我发现如果没有以下添加/更改,它就无法工作:

<TextBox Text="{Binding UploadNumber, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding Key="Enter" Command="{Binding FindUploadCommand}" />
    </TextBox.InputBindings>
</TextBox>
于 2016-06-09T07:00:57.490 回答
2

简短的回答是,如果没有代码隐藏,您将无法处理直接的键盘输入事件,但您可以使用 MVVM 处理InputBindings(如果您需要,我可以向您展示相关示例)。

你能提供更多关于你想在处理程序中做什么的信息吗?

使用 MVVM 并不能完全避免代码隐藏。它只是用于严格与 UI 相关的任务。一个主要的例子是具有某种类型的“数据输入表单”,当加载时,需要将焦点设置到第一个输入元素(文本框、组合框等)。您通常会为该元素分配一个 x:Name 属性,然后连接 Window/Page/UserControl 的“Loaded”事件以将焦点设置到该元素。这对模式来说是完全可以的,因为任务是以 UI 为中心的,与它所代表的数据无关。

于 2009-03-05T00:13:29.213 回答
1

我知道这个问题已经很老了,但我之所以提出这个问题是因为这种功能在 Silverlight (5) 中更容易实现。所以也许其他人也会来这里。

在找不到我要找的东西后,我写了这个简单的解决方案。原来这很简单。它应该适用于 Silverlight 5 和 WPF。

public class KeyToCommandExtension : IMarkupExtension<Delegate>
{
    public string Command { get; set; }
    public Key Key { get; set; }

    private void KeyEvent(object sender, KeyEventArgs e)
    {
        if (Key != Key.None && e.Key != Key) return;

        var target = (FrameworkElement)sender;

        if (target.DataContext == null) return;

        var property = target.DataContext.GetType().GetProperty(Command, BindingFlags.Public | BindingFlags.Instance, null, typeof(ICommand), new Type[0], null);

        if (property == null) return;

        var command = (ICommand)property.GetValue(target.DataContext, null);

        if (command != null && command.CanExecute(Key))
            command.Execute(Key);
    }

    public Delegate ProvideValue(IServiceProvider serviceProvider)
    {
        if (string.IsNullOrEmpty(Command))
            throw new InvalidOperationException("Command not set");

        var targetProvider = (IProvideValueTarget)serviceProvider.GetService(typeof(IProvideValueTarget));

        if (!(targetProvider.TargetObject is FrameworkElement))
            throw new InvalidOperationException("Target object must be FrameworkElement");

        if (!(targetProvider.TargetProperty is EventInfo))
            throw new InvalidOperationException("Target property must be event");

        return Delegate.CreateDelegate(typeof(KeyEventHandler), this, "KeyEvent");
    }

用法:

<TextBox KeyUp="{MarkupExtensions:KeyToCommand Command=LoginCommand, Key=Enter}"/>

请注意,这Command是一个字符串,而不是可绑定的ICommand。我知道这不是那么灵活,但它在使用时更干净,而且你 99% 的时间都需要它。虽然改变应该不是问题。

于 2011-09-01T13:26:43.460 回答