Using MV-VM with WPF, how do I instantiate a dialog using ViewModel?

I am using MV-VM with dialog boxes. The process that I use to create dialog boxes is as follows:

  • The ViewModel team wants to open a dialog.
  • It creates a ViewModel for the dialog (we will call it DialogViewModel).
  • It then passes the ViewModel to the DialogProvider to create the actual view. This allows me to check my dialogs, as the provider can provide either a real view or a test view.

Everything works. However, my current solution for DialogProvider is to use reflection to manually find the View class to instantiate based on the ViewModel name, for example:

var viewModelType = viewModel.GetType();
var dialogTypeName = Regex.Replace(viewModelType.Name, "ViewModel$", "Dialog");
var viewType = Assembly.GetExecutingAssembly().GetType(dialogTypeName);
if (viewType == null)
    throw new InvalidOperationException("Could not find view for given type.");

var dialog = (Dialog)viewType.GetConstructor(Type.EmptyTypes).Invoke(new object[0]);
dialog.DataContext = viewModel;
dialog.Owner = Application.Current.MainWindow;

return dialog;

, , ViewModel, ..

DataTemplate . , , , DataTemplate ContentPresenter DataTemplate DataType (. Josh Smith MVVM. # ( DialogProvider).

? , ContentPresenter #, DataTemplate, , Dialog???

+3
2

DialogProvider , , , ContentPresenter.

( DataTemplate ViewModel , UserControl).

, , , ContentPresenter DialogViewModel #, WPF apporiate View .

+3

(DI), View ( Dialog) ViewModel. unit test ViewModels MockView.

+1

Source: https://habr.com/ru/post/1724976/


All Articles