PlTaylor
PlTaylor

Reputation: 7515

How to get values out of a WPF Dialog Box with MVVM

What is the best way to get a value out of a WPF dialog box that was created with the MVVM pattern. My current code involves the extra step of getting the ViewModel and getting the appropriate variable out of it. I would like to avoid that step as it seems some what extraneous.

private void OpenDataSeriesWindow()
{
   var addVehicle = new AddResultsSeries();

   addVehicle.ShowDialog();

   AddResultsSeriesViewModel tempViewModel = (AddResultsSeriesViewModel)addVehicle.DataContext;
   PlotVariables.Add(tempViewModel.NewSelectedVariable);
}

Upvotes: 0

Views: 2746

Answers (1)

Dan Bryant
Dan Bryant

Reputation: 27495

I usually go about it this way:

  1. The ViewModel that wants to show a dialog constructs the CustomDialogViewModel for the specific dialog. It can also set up the ViewModel with initial parameters.

  2. The View provides an interface for displaying the dialog. For instance, if I had a CustomViewModel, the CustomWindow would implement ICustomView, which is injected into to the constructor of CustomViewModel. ICustomView would provide a method ShowCustomDialog(CustomDialogViewModel dialogViewModel).

  3. The ViewModel calls the ShowDialog method on the View interface. When the call returns, it can use the properties on the DialogViewModel to see the result.

This keeps the ViewModel nicely decoupled from the specific View implementation and allows you to inject a mock IView when unit testing. This allows you to write tests that sense the dialog has been opened with expected parameters and supply results accordingly.

Upvotes: 7

Related Questions