How do I close a window from its user control view model?

c#, datacontext, user-controls, viewmodel, wpf

Solution

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"/>

Problem

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); } } ```

Original source

Related problems