0

How can I assign the enter key to the on_Click event in the following code?

To make this clear I want to trigger the code inside the on_Click() method when the enter key is pressed.

Again, I'm using the MVVMLight framework.

ViewModel

namespace MyApp.ViewModel
{
    public class AppViewModel : ViewModelBase

    {
        public ICommand clickCommand { get; private set; }

        public AppViewModel()
        {
            clickCommand = new RelayCommand(() => on_Click());
        }

        private void on_Click()
        {      
            // button clicked     
        }
    }
}

XAML

<Button x:Name="myButton" 
        Content="Click Me" 
        HorizontalAlignment="right"
        Margin="0,84,72,0" 
        VerticalAlignment="Top" 
        Width="66" Height="25"
        Command="{Binding clickCommand}" Foreground="#FFF2F5FC" BorderBrush="{x:Null}">
    <Button.Background>
        <SolidColorBrush Color="#FF3DA5DB"/>
    </Button.Background>
</Button>
fs_tigre
  • 10,650
  • 13
  • 73
  • 146

1 Answers1

1

Great link shared by @shivani. most of the ways are covered there. One more thing you can do is to set IsDefault property of a button.

there is an inbuild feature available that you can set one button as a default to execute click event of that button on enter key press.

SO, you can go with IsDefault as well.

<Button x:Name="myButton" 
        Content="Click Me" 
        HorizontalAlignment="right"
        Margin="0,84,72,0" 
        VerticalAlignment="Top" 
        Width="66" Height="25" IsDefault="True"
        Command="{Binding clickCommand}" Foreground="#FFF2F5FC" BorderBrush="{x:Null}">
<Button.Background>
    <SolidColorBrush Color="#FF3DA5DB"/>
</Button.Background>

maulik kansara
  • 1,087
  • 6
  • 21