1

I have a save button and I want to use the MVVM design pattern, but I need to close the window once the save has been done, I looked a little on the web and saw that this is a lot of work, so i decided to make the window.close() on the code behind and all the saving logic on the view model.

How can I implement a button with a command binding and also an event handler?

Yogevnn
  • 1,320
  • 1
  • 16
  • 35

2 Answers2

0

Check out this answer which worked pretty well for me. You can pass the window itself as a command parameter and then use it in the viewmodel to close it.

Relevant XAML from that answer:

Command="{Binding CloseWindowCommand, Mode=OneWay}" 
CommandParameter="{Binding ElementName=TestWindow}"

Relevant ViewModel command handler from the same answer:

private void CloseWindow(Window window)
{
    if (window != null)
    {
       window.Close();
    }
}

You'll obviously also need to expose a command to bind to, in this case called CloseWindowCommand.

Community
  • 1
  • 1
Gigi
  • 26,290
  • 24
  • 96
  • 182
0

Just define the two in the button xaml like so:

<Button Command="{Binding SaveCommand}" Click="Button_click"/>
Shaaak
  • 578
  • 3
  • 9