MVVM パターンに従う WPF アプリケーションを開発しています。モーダルダイアログを表示するには、次の記事が示唆する方法に従おうとしています。 http://www.codeproject.com/Articles/36745/Showing-Dialogs-When-Using-the-MVVM-Pattern?fid=1541292&fr=26#xx0xx
しかし、この種の記事では、DialogService インターフェイスの ShowDialog メソッドが MainWindowViewModel から呼び出されていることがわかりました。
私のアプリケーションの状況は少し異なります。MainWindow.xaml には、ボタン Add を含む ChildView などのユーザー コントロールが含まれています。MainWindowViewModel には、ChildView にバインドされている ChildVM などの別の ViewModel が含まれています。ChildVM には AddCommand が含まれており、AddCommand に対応する AddExecute メソッドが呼び出されたときに Modal Dialog を表示する必要があります。どうすればそれを達成できますか?
編集されたコード
private Window FindOwnerWindow(object viewModel)
{
FrameworkElement view = null;
// Windows and UserControls are registered as view.
// So all the active windows and userControls are contained in views
foreach (FrameworkElement viewIterator in views)
{
// Check whether the view is an Window
// If the view is an window and dataContext of the window, matches
// with the viewModel, then set view = viewIterator
Window viewWindow = viewIterator as Window;
if (null != viewWindow)
{
if (true == ReferenceEquals(viewWindow.DataContext, viewModel))
{
view = viewWindow;
break;
}
}
else
{
// Check whether the view is an UserControl
// If the view is an UserControl and Content of the userControl, matches
// with the viewModel, then set view = userControl
// In case the view is an user control, then find the Window that contains the
// user control and set it as owner
System.Windows.Controls.UserControl userControl = viewIterator as System.Windows.Controls.UserControl;
if (null != userControl)
{
if (true == ReferenceEquals(userControl.Content, viewModel))
{
view = userControl;
break;
}
}
}
}
if (view == null)
{
throw new ArgumentException("Viewmodel is not referenced by any registered View.");
}
// Get owner window
Window owner = view as Window;
if (owner == null)
{
owner = Window.GetWindow(view);
}
// Make sure owner window was found
if (owner == null)
{
throw new InvalidOperationException("View is not contained within a Window.");
}
return owner;
}