Question

I'm having some difficulty finding simple examples while using WPF when it comes to control bindings and I'm hoping you can help me get my head around it with this simple example.

Can you please explain why this doesn't work and also a simple way to get it running?

I've looked at numerous tutorials but they are all still a little advanced for me at this stage I think so any help is greatly appreciated.

Thanks!

XAML:

<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" x:Class="DemoProject.MainWindow"
    xmlns:custom="clr-namespace:DemoProject"
    Title="DemoProject" >

    <TextBox x:Name="MyTextBox">
        <TextBox.InputBindings>
            <KeyBinding Key="Enter" Command="{x:Static custom:MainWindow.CommandEnterKeyPressed}" 
                CommandParameter="{Binding Path=Text, RelativeSource={RelativeSource AncestorType={x:Type TextBox}}}" />
        </TextBox.InputBindings>
    </TextBox>

    <Window.CommandBindings>
        <CommandBinding Command="{x:Static custom:MainWindow.CommandEnterKeyPressed}"
            Executed="CommandEnterKeyPressedExecuted" />
    </Window.CommandBindings>   
</Window>

C#:

namespace DemoProject
{
    public partial class MainWindow : Window
    { 
        private static RoutedUICommand CommandEnterKeyPressed;

        public MainWindow()
        {
            InitializeComponent();
        }

        public static RoutedUICommand CommandEnterKeyPressed = new RoutedUICommand();

        private void CommandEnterKeyPressedExecuted(object sender, CanExecuteRoutedEventArgs e)
        {
            MessageBox.Show("Enter key was pressed");
        }
    }
}

When I run this, I get the errors

"The member "CommandEnterKeyPressed" is not recognised or is not accessible" and "No overload for "'ommandEnterKeyPressed' matches delegate 'System.Windows.Input.ExecutedRoutedEventHandler'".

Is there something simple I'm missing?

Thanks.

Was it helpful?

Solution

Change CanExecuteRoutedEventArgs to ExecutedRoutedEventArgs

private void CommandEnterKeyPressedExecuted(object sender, CanExecuteRoutedEventArgs e)

Should be

private void CommandEnterKeyPressedExecuted(object sender, ExecutedRoutedEventArgs e)

CanExecuteRoutedEventArgs is used for CanExecute event. You should also remove this line

private static RoutedUICommand CommandEnterKeyPressed;

and leave only public declaration of your RoutedUICommand

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top