C#/ WPF:KeyBinding不触发命令

Jie*_*eng 10 c# wpf icommand

我已经宣布了 <InputBindings>

<UserControl.InputBindings>
    <KeyBinding Key="C" Modifiers="Ctrl" Command="{Binding CopyImageCommand}" />
    <KeyBinding Key="V" Modifiers="Ctrl" Command="{Binding PasteImageCommand}" />
</UserControl.InputBindings>
Run Code Online (Sandbox Code Playgroud)

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

<Button Command="{Binding CopyImageCommand}" Content="Copy" />
<Button Command="{Binding PasteImageCommand}" Content="Paste" />
Run Code Online (Sandbox Code Playgroud)

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

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

UPDATE

更完整的代码snipplet

<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="*" />
Run Code Online (Sandbox Code Playgroud)

UPDATE

我发现我需要把它KeyBindings放在MainWindow中,但命令在ViewModel,我怎样才能设置键绑定ShellView,然后绑定到命令中ShellViewModel

Gee*_*rik 6

确保您没有绑定错误.您设置用户控件的DataContext,但请确保命令可以绑定到它.有时,WPF只使用外观顺序,然后在命令之后设置DataContext.

可能VS的输出窗口已经显示命令的绑定错误.尝试将DataContext定义放在最前面(并教导自己为所有视图执行此操作).


Eup*_*ric 0

你用的是3.5还是4?

3.5 中的“功能”。UserControl.InputBindings 不是 dataContext 树的一部分,因此您无法绑定到绑定到父级的类的项目。例如。DataBinding 不起作用,您需要在代码中手动设置 DataBinding 或整个 KeyBinding。

其固定为4。