Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C#: WPF MVVM Command Binding vs. Event Callback

Tags:

c#

mvvm

wpf

xaml

What would be the point to using MVVM for the close action of File->Exit.

It seems like a lot of work to make a close command when you can simply create an event callback for the Click event. For something like this that doesn't have anything to do with data or business logic, I don't see the point to using MVVM approach. Why not just use the following:

xaml:

<MenuItem Header="_File" Background="WhiteSmoke">
    <MenuItem Name ="Exit" Tag="Exit" Header="Exit" Click="Exit_Click"/>                
</MenuItem>  

Code behind:

private void Exit_Click(object sender, RoutedEventArgs e)
{
    this.Close();
}
like image 639
Sean Thornton Avatar asked Jan 09 '23 01:01

Sean Thornton


1 Answers

For that case, you have a bit of an argument. If nothing else, closing the view could easily be construed as entirely view related, so a Click event handler makes sense to start with. View-related code goes in the view, not the VM.

However, I would challenge your notion that a Command is that hard to set up. Using a DelegateCommand: http://wpftutorial.net/DelegateCommand.html requires two lines of additional code:

public ICommand ExitCommand {get; private set;}

public MyViewModel()
{
    ExitCommand = new DelegateCommand(ExitApp);
}

The handler is the same either way. While Exit may not need a command, in general, ICommand is the right way to go and isn't actually that hard.

like image 121
BradleyDotNET Avatar answered Jan 11 '23 23:01

BradleyDotNET