0

I was wondering if there was a way to close a window when a property in the view model changes. In my situation I have a login window with an Ok button bound to a LoginCommand so that the function Login executes when Ok is clicked. If the login is successful, I want the window to close.

Now I know I could do this by adding an event handler on my button, which calls a function like this:

private void Button_Click(object sender, RoutedEventArgs e)
{
  DatabaseCredentialsViewModel vm = (this.DataContext as DatabaseCredentialsViewModel);
  vm.Login();

  if (vm.LoginSuccessful)
  {
    this.Close();
  }
}

But I was wondering if there was a way to close the window when LoginSuccessful property changes without having an event handler on my button (I like working only with command binding and not having event handlers on Click event).

Thank you

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Carl
  • 1,224
  • 2
  • 19
  • 35

3 Answers3

2

Here's a similar question, which filled my need.

Basically, you use an attached property for your window, which binds to a bool? property on your VM. When the VM property is set to something non-null, the attached property sets the Window's DialogResult, which will automatically close the window.

Community
  • 1
  • 1
Ben Straub
  • 5,675
  • 3
  • 28
  • 43
  • thank you for your answer! I'll look a little bit more into that because I've never had to add an attached property but if it's simple that's probably the best solution. – Carl Jun 09 '11 at 18:06
1

If you want you can try this different approach.
You can do this by associating the OK button with a command. Create an event such as LoginSuccess and when then add a window.Close() to the list of event callback. Then you have only to raise the LoginSuccess event to close the windows.
In my opinion, this respect the MVVM pattern defining an event that can be used for other trigger and not only for closing windows.

LoSciamano
  • 1,099
  • 10
  • 21
  • yeah that's probably the way i'll go. I agree it's the simplest way to do it without breaking MVVM pattern. thank you :) – Carl Jun 09 '11 at 18:02
0

You could do this fairly easily by creating an attached property or Behavior (from Blend SDK) that hooked into your Window.

I posted a sample behavior to the Expression Code Gallery which does something similar (though definitely different) - it prevents a window from being closed via a property on the VM. You could very easily adapt the code (included in the download) to just close the window on a property change.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373