Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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); }
    }
like image 559
user13070 Avatar asked Jun 15 '12 09:06

user13070


2 Answers

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"/>
like image 112
user13070 Avatar answered Sep 18 '22 16:09

user13070


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.

like image 38
GazTheDestroyer Avatar answered Sep 19 '22 16:09

GazTheDestroyer