Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF calling commands via events

The simplest way to do this is using an interaction trigger.

<Grid xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="SomeEvent">
            <i:InvokeCommandAction Command="{Binding Path=SomeCommand, Mode=OneWay}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</Grid>

I have added this for posterity sake.


You can use attached behaviors to achieve this. Marlon Grech has written the Attached Command Behaviors library to save you the trouble. Usage looks like this:

<Grid>
    <local:CommandBehaviorCollection.Behaviors>
        <local:BehaviorBinding Event="MouseRightButtonDown" Command="{Binding SomeCommand}" CommandParameter="A Command on MouseRightButtonDown"/>
    </local:CommandBehaviorCollection.Behaviors>
</Grid>

I'm afraid I don't think what you want to do is possible. Commands aren't delegates, so you can't write a command up to an event. I think your best option is to handle the Button.LostFocus event, and then manually execute the command from the handler.

There is nothing wrong with putting code in the code behind when using MVVM, it is just best to minimize it and keep the code to view related tasks only. I would call this code view related, so it would be find to put the code in the code behind.


<Grid MouseRightButtonDown ="{eb:EventBinding Command=SomeCommand, CommandParameter=$e}">

</Grid>

Command

{eb:EventBinding} (Simple naming pattern to find Command)

{eb:EventBinding Command=CommandName}

CommandParameter

$e (EventAgrs) 

$this or $this.Property

string

https://github.com/JonghoL/EventBindingMarkup