C#/WPF : KeyBinding not triggering Command

标签 c# wpf icommand

我已经声明了<InputBindings>

<UserControl.InputBindings>
    <KeyBinding Key="C" Modifiers="Ctrl" Command="{Binding CopyImageCommand}" />
    <KeyBinding Key="V" Modifiers="Ctrl" Command="{Binding PasteImageCommand}" />
</UserControl.InputBindings>

出于测试目的,我也添加了绑定(bind)到这些命令的按钮

<Button Command="{Binding CopyImageCommand}" Content="Copy" />
<Button Command="{Binding PasteImageCommand}" Content="Paste" />

我注意到当启用粘贴按钮时,当我按下 Ctrl-V 时没有任何反应。 Ctrl-C 似乎有效。为此,选择了一个列表框项目,我不确定它是否有任何区别。任何人都知道为什么是我的 PasteImageCommand不触发?

顺便说一句,我正在使用 .NET 4

更新

更完整的代码片段

<UserControl x:Class="QuickImageUpload.Views.ShellView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:vm="clr-namespace:QuickImageUpload.ViewModels"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <UserControl.InputBindings>
        <KeyBinding Key="C" Modifiers="Ctrl" Command="{Binding CopyImageCommand}" />
        <KeyBinding Key="V" Modifiers="Ctrl" Command="{Binding PasteImageCommand}" />
    </UserControl.InputBindings>
    <UserControl.DataContext>
        <vm:ShellViewModel />
    </UserControl.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="50" />
            <RowDefinition Height="*" />

更新

我发现我需要把 KeyBindings在主窗口中,但命令在 ViewModel 中,如何在 ShellView 中设置键绑定(bind)然后绑定(bind)到 ShellViewModel 中的命令?

最佳答案

确保您没有绑定(bind)错误。您设置了用户控件的 DataContext,但要确保命令可以绑定(bind)到它。有时,WPF 只使用出现顺序,DataContext 设置在命令之后。

可能 VS 的输出窗口已经显示了命令的绑定(bind)错误。尝试将 DataContext 定义置于顶部(并自学对所有 View 执行此操作)。

关于C#/WPF : KeyBinding not triggering Command,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3941404/

相关文章:

c# - SQL Server ADO.Net从SQL脚本检索错误信息

silverlight - Silverlight 中的 MVVM (ICommand)

c# - 在出现 OnlyOnFaulted 的情况下使用 TPL 时出现未处理的异常

c# - SingleOrDefault 和 FirstOrDefault 返回缓存数据

c# - 如何从 ComboBox 控件获取 ToggleButton

c# - Model3DCollection 和 Model3DGroup 有什么区别?

c# - 如何在 MVVM 中对异步 ICommand 进行单元测试?

wpf - 如何在WPF中将三步操作更改为命令?

c# - 为逗号分隔字符串中的每个值遍历数组

c# - DataTrigger 绑定(bind)到 UserControl 依赖属性