Question

In my Application i have a MainWindow that import over MEFedMVVM the ViewModel:

xmlns:mefed="clr-namespace:MEFedMVVM.ViewModelLocator;assembly=MEFedMVVM.WPF"
mefed:ViewModelLocator.ViewModel="MainViewModel"

And now i have my ViewModel too that realize the ViewModel:

[ExportViewModel("MainViewModel")]
public class MainViewModel: ViewModelBase

In my ViewModel i have a ICommand property for closing the window. The event for closing can comes from anywhere. And with help from the Cinch Framework 2.0 i realize a Simplecommand with Execute methode.

Question

How can i Close the Window from my execute methode? Over the dependency injection i haven't a constructor i can't register an event or give the view as parameter to the viewmodel.

Edit

However, a possibility which I think is not nice:

Call this in the methode

Application.Current.MainWindow.Close()
Was it helpful?

Solution

You can achieve this by writing an ICommand that passes the Window instance in as a parameter.

A good example is available here: How can I assign the 'Close on Escape-key press' behavior to all WPF windows within a project?

In that post the ICommand is eventually bound to a KeyBinding (so that the Escape key can be used to close the window) but you would be able to bind the command to any button or invoke it from anywhere within the view. The important part is to use a RelativeSource on your command parameter binding to reference the Window that you want to close

Edit in response to comments

The command is a singleton, but there is no requirement for it to be - it is only a singleton because it is stateless and it makes the binding easier. It acquires a reference to the Window through binding, so for a UserControl you can just use:

<Button Command="{x:Static mynamespace:CloseWindowCommand.Instance}"
    CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=Window}}" Content="Close My Parent Window" />

To be able to call it from view model code is slightly more complicated and needs a different approach; a good example can be found here: http://gallery.expression.microsoft.com/WindowCloseBehavior

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top