I have a window which hosts various UserControl's as pages. Is it possible to close the window which I have no reference to from within the usercontrol's datacontext? Simplified details:
SetupWindow
public SetupWindow()
{
InitializeComponent();
Switcher.SetupWindow = this;
Switcher.Switch(new SetupStart());
}
public void Navigate(UserControl nextPage)
{
this.Content = nextPage;
}
SetupStart UserControl
<UserControl x:Class="...">
<UserControl.DataContext>
<local:SetupStartViewModel/>
</UserControl.DataContext>
<Grid>
<Button Content="Continue" Command="{Binding ContinueCommand}"/>
</Grid>
</UserControl>
SetupStartViewModel
public SetupStartViewModel()
{
}
private bool canContinueCommandExecute() { return true; }
private void continueCommandExectue()
{
Switcher.Switch(new SetupFinish());
}
public ICommand ContinueCommand
{
get { return new RelayCommand(continueCommandExectue, canContinueCommandExecute); }
}
I managed to find a solution from an answer here: How to bind Close command to a button
View-Model:
public ICommand CloseCommand
{
get { return new RelayCommand<object>((o) => ((Window)o).Close(), (o) => true); }
}
View:
<Button Command="{Binding CloseCommand}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}}" Content="Close"/>
I do this by having a RequestClose
event in my ViewModel that it can raise when it wants the view to close.
This is then hooked up to the window's Close()
command by the code that creates the window. eg
var window = new Window();
var viewModel = new MyViewModel();
window.Content = viewModel;
viewModel.RequestClose += window.Close;
window.Show()
This way all the stuff to do with window creation is handled in one place. Neither the view, or the viewmodel know about windows.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With