我正在开发遵循MVVM模式的WPF应用程序。为了显示模态对话框,我试图按照以下文章的建议。 http://www.codeproject.com/Articles/36745/Showing-Dialogs-When-Using-the-MVVM-Pattern?fid=1541292&fr=26#xx0xx使用服务定位器的MVVM模式对话框
但是在这些文章中,我观察到,DialogService接口的ShowDialog方法是从MainWindowViewModel调用的。
我在申请中的情况稍有不同。 MainWindow.xaml包含一个用户控件,声称包含一个Add按钮的ChildView。 MainWindowViewModel包含另一个ViewModel,它说与ChildView绑定的ChildVM。 ChildVM包含AddCommand,我需要在AddExecute方法 对应的AddCommand被调用时显示模态对话框。 我该怎么做到这一点?
编辑代码
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;
}
嗨@Anirban,按照本文从http://www.codeproject.com/Articles/332615/WPF-Master-Details-MVVM-Application看看如何模态对话框的作品。我已经使用这篇文章来帮助我创建我的应用程序。希望这可以帮助! – 2013-03-05 11:05:53
该方法与我提供的链接相同。 – 2013-03-05 13:55:15
你有解决方案吗? – Marc 2013-03-06 07:50:27