Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#/WPF: KeyBinding not triggering Command

Tags:

c#

wpf

icommand

I have declared <InputBindings>

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

For testing purposes, I have added buttons bound to those commands too

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

I noticed that when the paste button is enabled, when i press Ctrl-V nothing happens. Ctrl-C seems to work. For that, a list box item is selected, I am not sure if it makes any difference. Anyone knows why is my PasteImageCommand not triggering?

I am using .NET 4 btw

UPDATE

A fuller code 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="*" />

UPDATE

I found out I need to put the KeyBindings in the MainWindow, but the commands are in the ViewModel, how can i set key bindings in the ShellView which then binds to commands in the ShellViewModel?

like image 508
Jiew Meng Avatar asked Oct 15 '10 10:10

Jiew Meng


1 Answers

Make sure that you are not having binding errors. You set the DataContext of the user control, but make sure that the commands can bind to it. Sometimes, WPF just uses the order of appearance, and the DataContext is set later then the commands.

Probably, the output window of VS already shows binding errors for the commands. Try putting the DataContext definition on top (and teach yourself to do this for all views).

like image 60
Geert van Horrik Avatar answered Sep 21 '22 21:09

Geert van Horrik