What event(s) trigger a command in a button?

2019-09-05 00:39发布

问题:

so i have a question relating to a project i'm working on:

what events are used to trigger a command in a button control? is it only the click event?

because when i click on a button my command will be executed after my mouse button is released? so thats why i want to know.

<Button x:Name="ClickButton" Content="Click here" HorizontalAlignment="Left" Margin="325,123,0,0" VerticalAlignment="Top" Width="75" Command="{Binding ClickHereCommand}"/>

Code in the ViewModel

  public ICommand ClickHereCommand => (new CommandHandler(() => IsGoingUp(), _canExecute));

    public void IsGoingUp()
    {
      Console.WriteLine("Moving up...");
    }

回答1:

By default, the Command property is indeed bound to the Click event. You can bind your Command property to other events as shown here: https://stackoverflow.com/a/20356042/1166719.

Though if you just want to bind your Command to another mouse event, the ClickMode property is what you're looking for: https://msdn.microsoft.com/en-US/library/system.windows.controls.primitives.buttonbase.clickmode(v=vs.110).aspx



回答2:

Events are raised in relation to a controls state. That is, when a button is clicked, or when a mouse moves over it etc.

If you want a list of the available events, in the designer, select the button then bring up properties (F4). Then click the lightning button in the properties window. This will list all the events for the selected control. You can also create methods for handling these events from here.

Here is a list of events for a button control

https://msdn.microsoft.com/en-us/library/system.windows.controls.button_events(v=vs.110).aspx