0

I have seen many examples over the net but I am not able to figure out what i am doing wrong here. I need to close a view from a view model. Below is the code i have tried:

ViewModel:

public class ViewModel
{
    public event EventHandler RequestClose;
    public ViewModel()
    {

    }
}

//Calling the event from view model to close the view from a method in View Model This event is called on a button click

private void Download()
{
//Download Logic
if(RequestClose != null)
                RequestClose(this,EventArgs.Empty);
 }

View:

ViewModel vm = new ViewModel();
vm.RequestClose += delegate(object sender, EventArgs args) {this.Close();}
this.DataContext = vm;
user2480288
  • 619
  • 2
  • 11
  • 28

3 Answers3

1

You fire the RequestClose event in the ViewModel constructor which is too early to be catched by the event registration.

shahar eldad
  • 861
  • 1
  • 12
  • 31
0

The best MVVM solution is to use an attached behavior, as outlined in the top rated answer to this question How should the ViewModel close the form?

Community
  • 1
  • 1
Peregrine
  • 4,287
  • 3
  • 17
  • 34
-1

I faced a similar problem earlier, and did the following: In the viewmodel, create a command that you can bind to (I personally use MvvmLight and its RelayCommand)

public class ViewModel
{
   public RelayCommand<object> CloseWindowCommand {get; private set;}

   public ViewModel()
   {
      CloseWindowCommand = new RelayCommand<object>(CloseTheWindow);
   }

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

In my view, I have button that triggers this command, e.g.

Button Content="Close" Command="{Binding CloseWindowCommand}" CommandParameter="{Binding ElementName=NameOvViewModel}"

I realize now, that this may require the use of MvvmLight, but I hope it offers some guidance on a possible solution to your question.

SimonAx
  • 1,176
  • 1
  • 8
  • 32