Найти в Дзене
Заметки БыдлоКодера

WPF MVVM C# Закрыть окно

Это заметка. Для закрытия формы по правилам MVVM, требуется проделать следующие. Создать класс: DelegateCommand наследующий ICommand, рисунок 1. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace FiasView.MVVM.DelegateCommand { public class DelegateCommand : ICommand { private Action<object> _execute; private Func<object, bool> _canExecute; public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } public DelegateCommand(Action<object> _execute, Func<object, bool> _canExecute = null) { this._execute = _execute; this._canExecute = _canExecute; } public bool CanExecute(object parameter) { return this._canExecute == null || this._canExecute(para

Всем привет!
Это заметка.

Для закрытия формы по правилам MVVM, требуется проделать следующие.

Создать класс: DelegateCommand наследующий ICommand, рисунок 1.

DelegateCommand Class
DelegateCommand Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace FiasView.MVVM.DelegateCommand
{
public class DelegateCommand : ICommand
{
private Action<object> _execute;
private Func<object, bool> _canExecute;
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public DelegateCommand(Action<object> _execute, Func<object, bool> _canExecute = null)
{
this._execute = _execute;
this._canExecute = _canExecute;
}
public bool CanExecute(object parameter)
{
return this._canExecute == null || this._canExecute(parameter);
}
public void Execute(object parameter)
{
this._execute(parameter);
}
}
}

Далее идем в View проекта и редактируем XAML.

Windows Interactivity
Windows Interactivity

Требуется добавить Windows.Interactivity.

Windows Interactivity
Windows Interactivity

Отлично, теперь мы можем работать с Windows Interactivity.

Добавляем кнопке закрытия данный код:

Interaction.Triggers
Interaction.Triggers

Интерактивные триггеры дают нам возможность вызвать команду и передать параметр, а именно наше окно.

Обратите внимание, CommandParameter = {Binding ElementName=MainWin}.

Мы передаем параметр, по его имени, имя нашего окна.

<Label Content="X" FontSize="20" Foreground="White" Background="{x:Null}" Grid.Column="10" Margin="0,0,0,3">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseUp">
<i:InvokeCommandAction Command="{Binding _CloseButton}" CommandParameter="{Binding ElementName=MainWin}">
</i:InvokeCommandAction>
</i:EventTrigger>
</i:Interaction.Triggers>
</Label>

Отправляемся в ViewModel.

Добавляем наш DelegateCommand.

DelegateCommand _CloseButton
DelegateCommand _CloseButton

X - это передаваемый параметр.

CloseButton
CloseButton

Создаем в ViewModel метод CloseButton, который принимает переменную типа object.

Данный метод позволяет выключить форму и тем самым завершить работу проекта.

Если у кого-то есть более изящный способ, пишите!

Всем спасибо за внимание!