I know that I'm a little late for this question, but this is what I use sometime now, and it works like a charm.
DashboardViewModel viewModel; public DashboardView() { InitializeComponent(); viewModel = new DashboardViewModel(); viewModel.RequestClose += (s, e) => Application.Current.Dispatcher.Invoke(this.Close); viewModel.RequestMinimize += (s, e) => Application.Current.Dispatcher.Invoke(() => { this.WindowState = WindowState.Minimized; }); DataContext = viewModel; }
and something like this in your view
#region Public Event Handlers public event EventHandler<EventArgs> RequestClose; public event EventHandler<EventArgs> RequestMinimize; #endregion
Using ICommand ...
#region ICommand Members public ICommand CloseCommand { get; private set; } public ICommand MinimizeCommand { get; private set; }
Set up commands ...
private void SetupCommands() { CloseCommand = new RelayCommand(CloseApplication); MinimizeCommand = new RelayCommand(MinimizeApplication); }
Here is the RelayCommand class.
public class RelayCommand : ICommand { #region Private Readonly Properties private readonly Action<object> executeCommand; private readonly Predicate<object> canExecute; #endregion #region Constructors public RelayCommand(Action<object> execute) : this(execute, null) { } public RelayCommand(Action<object> execute, Predicate<object> canExecute) { if (execute == null) throw new ArgumentNullException("execute"); this.executeCommand = execute; this.canExecute = canExecute; } #endregion #region Public ICommand Members public bool CanExecute(object parameter) { return canExecute == null ? true : canExecute(parameter); } public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public void Execute(object parameter) { executeCommand(parameter); } #endregion }
And some example methods ...
private void MinimizeApplication(object obj) { RequestMinimize(this, new EventArgs()); } private void CloseApplication(object obj) { RequestClose(this, new EventArgs()); }
Hope this helps!
Edd Dec 31 '15 at 21:00 2015-12-31 21:00
source share