我正在开发一个遵循 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 包含一个用户控件,例如 ChildView,其中包含一个按钮 Add。MainWindowViewModel 包含另一个 ViewModel,例如 ChildVM,它与 ChildView 绑定。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;
}