我已经声明了<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/