I was making a two-screen application with WPF.I'm trying to rewrite this to an MVVM pattern using Prism.
Simplified Example:
MainWindow, SubWindow
class.MainWindow
, Button_Click
is called and SubWindow
is displayed.MainWindow.xaml.cs
looks like this:public partial class MainWindow:Window
{
SubWindow sub;
private void Button_Click (object sender, RoutedEventArgse)
{
if(sub==null)
{
sub=new SubWindow();
sub.Closed+=(s,_e)=>sub=null;
sub.Show();
}
sub.Activate();
}
}
How do I write equivalent processing in Prism?I don't think it's MVVM-like to generate an instance of SubWindow
in View or ViewModel, or Show, Activate
, so I don't know how it works anymore.
All you need is
as shown in the code provided.SubWindow
.If it's already there, just activate it instead of creating a new instanceShowDialog
(MainWindow
can also be operated)and so on.
As a matter of concern, I looked at the IDialogService
sample (https://prismlibrary.com/docs/wpf/dialog-service.html), but I couldn't find a way to activate the SubWindow
on top of multiple screens.
Thank you for your cooperation.
c# wpf mvvm
For example,
You can use a delegate to insert features from the "outside" class that invokes the MainWindow.
It also describes how to close the screen;
MainWindowViewModel:
public Action RequestClose;
public Action RequestToSubWindow;
public Action <string > RequestToSubWindow2;
App.xaml.cs:
protected override void OnStartup (StartupEventArgse)
{
base.OnStartup(e);
varwnd = new MainWindow();
varmainVM = new MainWindowViewModel();
// When the ViewModel asks to be closed, close the window.
mainVM.RequestClose+=delegate{
wnd.Close();
};
mainVM.RequestToSubWindow+=displaySubWindow;
mainVM.RequestToSubWindow2+=displaySubWindow2;
wnd.DataContext=mainVM;
wnd.Show();
}
// If you do not want to have arguments in ViewModel in SubWindow
private static Action displaySubWindow=()=>{
var subWnd = new SubWindow();
var subVM = new SubViewModel();
// When the ViewModel asks to be closed, close the window.
subVM.RequestClose+=delegate
{
subWnd.Close();
};
subWnd.DataContext=subVM;
subWnd.ShowDialog();
};
// To have ViewModel arguments in SubWindow
private static Action <string > displaySubWindow2=(name_)=>{
var subWnd2 = new SubWindow2();
var subVM2 = new Sub2ViewModel(name_);
// When the ViewModel asks to be closed, close the window.
subVM2.RequestClose+=delegate
{
subWnd2.Close();
};
subWnd2.DataContext=subVM2;
subWnd2.Show();
};
Reference Site:
https://docs.microsoft.com/ja-jp/archive/msdn-magazine/2009/february/patterns-wpf-apps-with-the-model-view-viewmodel-design-pattern
I agree with the question "Not MVVM-like" but it is in the Microsoft documentation.
I can't say that this answer is pretty because it's a blatant code, so if there's any other way, I'd like to use it.
© 2024 OneMinuteCode. All rights reserved.