Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put events when using MVVM?

Should I put all events in views code behind or there is a more proper way, like place commands in ViewModel? For example, I want to open Tab on double click on the datagrid row, where should I handle this event?

like image 478
Mrg Gek Avatar asked Sep 19 '15 15:09

Mrg Gek


People also ask

When should MVVM be used?

MVVM separates your view (i.e. Activity s and Fragment s) from your business logic. MVVM is enough for small projects, but when your codebase becomes huge, your ViewModel s start bloating. Separating responsibilities becomes hard. MVVM with Clean Architecture is pretty good in such cases.

Is MVVM slow?

MVVM Done Right is Slow In a large application, you might need to loop through the data multiple times to make sure it has all recalculated correctly. If you just use the framework and let the framework deal with your sloppy code, this can make the system incredibly slow.

What is MVVM command?

Commands are an implementation of the ICommand interface that is part of the . NET Framework. This interface is used a lot in MVVM applications, but it is useful not only in XAML-based apps.


1 Answers

Kyle is correct in that your handlers should appear in the view model. If a command property doesn't exist then you can use an interaction trigger instead:

<DataGrid>
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="MouseDoubleClick">
            <i:InvokeCommandAction Command="{Binding Mode=OneWay, Path=OpenClientCommand}" CommandParameter="{Binding ElementName=searchResults, Path=SelectedItems}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

    ... other stuff goes here ...

</DataGrid>

Or you can use MVVM Lite's EventToCommand, which also allows you to pass in the message parameters:

<i:Interaction.Triggers>
    <i:EventTrigger EventName="Closing">
        <cmd:EventToCommand Command="{Binding ClosingCommand}" PassEventArgsToCommand="True" />
    </i:EventTrigger>
</i:Interaction.Triggers>

Which is used in in this case to cancel the window close event in response to the "Are you sure you want to quit?" dialog:

public ICommand ClosingCommand { get { return new RelayCommand<CancelEventArgs>(OnClosing); } }

private void OnClosing(CancelEventArgs args)
{
    if (UserCancelsClose())
        args.Cancel = true;
}

Relevant namespaces are as follows:

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
xmlns:cmd ="http://www.galasoft.ch/mvvmlight"
like image 156
Mark Feldman Avatar answered Oct 14 '22 03:10

Mark Feldman