Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF event binding from View to ViewModel?

Tags:

c#

binding

wpf

What is the best way to bind a WPF event in the View to the ViewModel?

I have a drop event in my View but I want to replace it to the ViewModel due binding.

Found several solutions but none of them did what I expected.

View code:

    <TextBox      AllowDrop="True"      PreviewDrop="email_Drop" /> 
like image 779
jefsmi Avatar asked Oct 24 '11 14:10

jefsmi


1 Answers

One way to handle events in MVVM and XAML is to use the Blend Interactivity features. This namespace contains the InvokeCommandAction and the CallMethodAction classes.

InvokeCommandAction lets you bind any event to a view-model command while CallMethodAction lets you bind any event to a view-model method.

For example if you want to bind the DoubleClick event of a Button to a view-model command you would do like this:

<Button>     <i:Interaction.Triggers>         <i:EventTrigger EventName="MouseDoubleClick">             <i:InvokeCommandAction Command="{Binding Path=DoSomethingCommand}"/>         </i:EventTrigger>     </i:Interaction.Triggers> </Button> 

And declaring this namespace:

xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 

All you need to reference it in your projects is to install Expression Blend or the Expression Blend SDK.

like image 180
Ucodia Avatar answered Oct 06 '22 04:10

Ucodia