我正在開發遵循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