Самый простой способ заключается в реализации dialogservice и использовать инъекции зависимостей, чтобы ввести услугу в к ViewModel. Хорошо иметь зависимость от интерфейса, но не иметь зависимости от конкретной реализации.
Ниже интерфейс я использую:
namespace DialogServiceInterfaceLibrary
{
public enum MessageBoxButton
{
// Summary:
// The message box displays an OK button.
OK = 0,
//
// Summary:
// The message box displays OK and Cancel buttons.
OKCancel = 1,
//
// Summary:
// The message box displays Yes, No, and Cancel buttons.
YesNoCancel = 3,
//
// Summary:
// The message box displays Yes and No buttons.
YesNo = 4,
}
public enum MessageBoxResult
{
// Summary:
// The message box returns no result.
None = 0,
//
// Summary:
// The result value of the message box is OK.
OK = 1,
//
// Summary:
// The result value of the message box is Cancel.
Cancel = 2,
//
// Summary:
// The result value of the message box is Yes.
Yes = 6,
//
// Summary:
// The result value of the message box is No.
No = 7,
}
// Summary:
// Specifies the icon that is displayed by a message box.
public enum MessageBoxIcon
{
// Summary:
// No icon is displayed.
None = 0,
//
// Summary:
// The message box contains a symbol consisting of white X in a circle with
// a red background.
Error = 16,
//
// Summary:
// The message box contains a symbol consisting of a white X in a circle with
// a red background.
Hand = 16,
//
// Summary:
// The message box contains a symbol consisting of white X in a circle with
// a red background.
Stop = 16,
//
// Summary:
// The message box contains a symbol consisting of a question mark in a circle.
Question = 32,
//
// Summary:
// The message box contains a symbol consisting of an exclamation point in a
// triangle with a yellow background.
Exclamation = 48,
//
// Summary:
// The message box contains a symbol consisting of an exclamation point in a
// triangle with a yellow background.
Warning = 48,
//
// Summary:
// The message box contains a symbol consisting of a lowercase letter i in a
// circle.
Information = 64,
//
// Summary:
// The message box contains a symbol consisting of a lowercase letter i in a
// circle.
Asterisk = 64,
}
public interface IDialogService
{
bool OpenFileDialog(bool checkFileExists,string Filter, out string FileName);
void OpenGenericDialog(object Context,IRegionManager RegionManager);
MessageBoxResult ShowMessageBox(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon);
}
И реализация:
public class DialogService : IDialogService
{
public bool OpenFileDialog(bool checkFileExists, string Filter, out string FileName)
{
FileName = "";
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = false;
//openFileDialog.Filter = "All Image Files | *.jpg;*.png | All files | *.*";
openFileDialog.Filter = Filter;
openFileDialog.CheckFileExists = checkFileExists;
bool result = ((bool)openFileDialog.ShowDialog());
if (result)
{
FileName = openFileDialog.FileName;
}
return result;
}
public void OpenGenericDialog(object Context,IRegionManager RegionManager)
{
GenericDialogWindow dlg = new GenericDialogWindow(Context,RegionManager);
dlg.Owner = System.Windows.Application.Current.MainWindow;
dlg.Show();
}
public MessageBoxResult ShowMessageBox(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon)
{
return (DialogServiceInterfaceLibrary.MessageBoxResult)System.Windows.MessageBox.Show(message, caption,
(System.Windows.MessageBoxButton)buttons,
(System.Windows.MessageBoxImage)icon);
}
}
Затем впрыскивают IDialogservice в ViewModel. Интерфейс и конкретная реализация, как правило, в другой сборке
MainWindowViewModel(IDialogService dialogservice){
_dialogservice = dialogservice;
}
private void ShowUsercontrol()
{
_dialogservice.ShowMessageBox(... //you get what i mean ;-)
}
dialogservice умеет открывать стандартные диалоги окна, как диалог открытия файла. Также можно использовать общую версию, но тогда вам нужно понять призму, которая немного сложнее. Prism также позволяет использовать запросы взаимодействия для связи с viewmodel до представления. Я предпочитаю этот способ работы в призме, но если вы не знаете, что призма забудет это замечание. Это, вероятно, слишком сложно для простого окна подтверждения. Так как простое диалоговое обслуживание, подобное этому, идеально подходит для простого окна подтверждения.
Имея зависимости, введенные через конструктор модели, перемещает вас уже в правильном направлении с помощью инверсии контейнера управления. И позволяет упростить модульное тестирование, потому что вы можете издеваться над инъецированными интерфейсами, чтобы проверить, правильно ли они вызваны и т. Д.
Вы можете либо реализовать [диалоговое окно] (http://stackoverflow.com/a/28710441/220636), чтобы открыть диалоговое окно, либо использовать [сообщения] (http://stackoverflow.com/a/31161068/220636) для достижения чистого разделения проблем на MVVM-пути. – nabulke
Здесь возникает несколько вопросов о том, как отображать новое представление (например, диалоговое окно) в ответ на событие ViewModel. То, что вы уже сделали, прекрасно, если оно работает. С точки зрения пуриста, вы можете взглянуть на использование DependencyProperties, чтобы предоставить View с механизмом обнаружения того, что ViewModel хочет получить окно подтверждения, не имея VeiwModel, чтобы вызвать прямо в View. –