我正在开发一个遵循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包含另一个名为ChildVM的ViewModel,该ViewModel与ChildView绑定。 ChildVM包含AddCommand,并且当调用AddCommand的AddExecute方法时,我需要显示模态对话框。 我该如何实现?
我的应用程序情况略有不同。 MainWindow.xaml包含一个名为ChildView的用户控件,其中包含一个按钮Add。 MainWindowViewModel包含另一个名为ChildVM的ViewModel,该ViewModel与ChildView绑定。 ChildVM包含AddCommand,并且当调用AddCommand的AddExecute方法时,我需要显示模态对话框。 我该如何实现?
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;
}