1

I have a functional MVVM patterned SL app with a RadWindow (essentially a ChildWindow), that I would like to remove the code-behind in my view that shows the window using its ShowDialog. Both the main view and the window is bound to the same ViewModel if that helps.

The button has both a ViewModel command using a MVVMLight RelayCommand to handle setting state as well as the event handler in the View.

The ultimate solution/pattern will be reused 20+ times so something better than code-behind would be great.

Thoughts?

private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
    var window = new RadWindowTest.Controls.ChildWindow1();

    window.Closed += new System.EventHandler<Telerik.Windows.Controls.WindowClosedEventArgs>(window_Closed);

    window.ShowDialog();

}
AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70
rusty
  • 87
  • 7

1 Answers1

0

In this case I would suggest you implement DialogService. This service you can inject into your view model, for testing you will have to inject an instance that does not depend on the view, thus maintaining testability. You can use the ViewModelLocator to make this service available to your application.

Another approach would be to implement a ViewBase class that implements an interface that allows you to display the dialog. This interface is now used by the ViewModel to display a dialog. Again to test you need to provide a different implementation of the interface. A sample can be found here.

Both ideas revolve around the same concept of factoring out the function that shows the dialog. In order to strictly de-couple the View and the ViewModel you will have to think about how the ViewModel specifies which dialog has to be shoen, and how the dialog resut or dialog model is returned to the calling ViewModel.

Which approach is better is open to your judgement. Personally I prefer the first approach as I do not have to inherit the views from a common base class.

PS: Use a command to get to the point in your ViewModel where you want to show the dialog. Using a dialog service should need no code behind.

AxelEckenberger
  • 16,628
  • 3
  • 48
  • 70
  • Awesome, thank you. Do you feel that MVVMLight Messages could be used as well or is the DialogService more pure (agnostic)? – rusty Jun 28 '11 at 18:28
  • Obviously you could, but as it is a child window you are showing I believe that calling a method fits more. In addition sending a message is a broadcast where you do not know who might react to it. So you may end up with multiple dialogs poping up if you are not careful. – AxelEckenberger Jun 28 '11 at 22:23
  • I appreciate the discussion, I will work towards doing as you suggest. – rusty Jun 29 '11 at 13:43
  • That was perfect, I implemented a modified DialogService and it looks and works great. Thank you. – rusty Jun 29 '11 at 19:49