Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a ChildWindow with Cancel button using MVVM Light Toolkit

I'm new to MVVM and trying to figure out how to close a ChildWindow with the traditional Cancel button using MVVM Light Toolkit.

In my ChildWindow (StoreDetail.xaml), I have :

<Button x:Name="CancelButton" Content="Cancel" Command="{Binding CancelCommand}" />

In my ViewModel (ViewModelStoreDetail.cs), I have :

public ICommand CancelCommand { get; private set; }

public ViewModelStoreDetail()
{
    CancelCommand = new RelayCommand(CancelEval);
}

private void CancelEval()
{
    //Not sure if Messenger is the way to go here...
    //Messenger.Default.Send<string>("ClosePostEventChildWindow", "ClosePostEventChildWindow");
}
like image 921
Jérôme Oudoul Avatar asked Apr 12 '11 15:04

Jérôme Oudoul


2 Answers

private DelegateCommand _cancelCommand;

public ICommand CancelCommand
{
    get
    {
        if (_cancelCommand == null)
            _cancelCommand = new DelegateCommand(CloseWindow);
        return _cancelCommand;
    }
}

private void CloseWindow()
{
    Application.Current.Windows[Application.Current.Windows.Count - 1].Close();
}
like image 131
user841960 Avatar answered Oct 26 '22 23:10

user841960


If you displayed your child window by calling ShowDialog(), then you can simply set the IsCancel property of your button control to "True".

<Button Content="Cancel" IsCancel="True" />

It becomes the same as clicking the X button on the window, or pressing ESC on the keyboard.

like image 33
bugged87 Avatar answered Oct 27 '22 00:10

bugged87