The WindowManager - canton7/Stylet GitHub Wiki
In a traditional View-first approach, if you want to display a new window or dialog, you create a new instance of the View, then call .Show()
or .ShowDialog()
.
In a ViewModel-first approach, you can't interact directly with the views, so you can't do this. The WindowManager solves this problem - calling IWindowManager.ShowWindow(someViewModel)
will take that ViewModel, find its view, instantiate it, bind it to that ViewModel, and display it.
C# | VB.NET |
class SomeViewModel
{
private IWindowManager windowManager;
public SomeViewModel(IWindowManager windowManager)
{
this.windowManager = windowManager;
}
public void ShowAWindow()
{
var viewModel = new OtherViewModel();
this.windowManager.ShowWindow(viewModel);
}
public void ShowADialog()
{
var viewModel = new OtherViewModel();
bool? result = this.windowManager.ShowDialog(viewModel);
// result holds the return value of Window.ShowDialog()
if (result.GetValueOrDefault(true))
{
// DialogResult was set to true
}
}
} |
Class SomeViewModel
Private windowManager As IWindowManager
Public Sub New(ByVal windowManager As IWindowManager)
Me.windowManager = windowManager
End Sub
Public Sub ShowAWindow()
Dim viewModel = New OtherViewModel()
Me.windowManager.ShowWindow(viewModel)
End Sub
Public Sub ShowADialog()
Dim viewModel = New OtherViewModel()
Dim result As Boolean? = Me.windowManager.ShowDialog(viewModel)
' Result holds the return value of Window.ShowDialog()
If result.GetValueOrDefault(True) Then
' DialogResult was set to true
End If
End Sub
End Class |
Nice and easy! In addition, the introduction of the IWindowManager (rather than calling methods directly on the ViewModel) makes testing a lot easier.
To close a window or dialog from its ViewModel, use Screen.RequestClose
, like this:
C# | VB.NET |
class ViewModelDisplayedAsWindow
{
// Called by pressing the 'close' button
public void Close()
{
this.RequestClose();
}
}
class ViewModelDisplayedAsDialog
{
// Called by pressing the 'OK' button
public void CloseWithSuccess()
{
this.RequestClose(true);
}
} |
Class ViewModelDisplayedAsWindow
' Called by pressing the 'close' button
Public Sub Close()
Me.RequestClose()
End Sub
End Class
Class ViewModelDisplayedAsDialog
' Called by pressing the 'OK' button
Public Sub CloseWithSuccess()
Me.RequestClose(True)
End Sub
End Class |