views:

1452

answers:

4

Hi,

Is it possible to call a command via an event in WPF?

I have a save button that when pressed calls a command, this is pressed when you have finished editing a textbox, it also passes an object as a command parameter

 <Button Content="Save"  Command="{Binding DataContext.SaveQueueTimeCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ItemsControl}}}" CommandParameter="{Binding}" />

What I would ideally like to do is call this command and pass the object as a parameter when the textbox loses focus, rather than having to press the button, something like:

 <Button LostFocus="{Binding SaveQueueTimeCommand}" />

And still somehow pass the object as a parameter. Is there a way to acheive this without using code behind as I am using the MVVM pattern

Thanks for your time

+1  A: 

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.

Andy
Yeah that makes sense, thanks for your time :)
+2  A: 

Yes, it is possible but requires you to have some code that attaches itself to the event and executes your command in response. See this for an example and a framework for doing this.

Bojan Resnik
+5  A: 

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>

HTH, Kent

Kent Boogaart
A: 

Here is a very nice framework which simply works out of box, and sample application is self descriptive (time saver):

http://blogs.microsoft.co.il/blogs/tomershamam/archive/2009/04/14/wpf-commands-everywhere.aspx?CommentPosted=true#commentmessage

It also has some nice features like multiple commands execution and 'property changed' command execution

tomaszkubacki