Donate

How To Close A Window Via Click Command Using MVVM In WPF

Good day!

Here's a simple WPF tutorial on how to close a window in WPF thru button click which applies the MVVM pattern. For simplicity sake, I'll demonstrate by using Menu item with a command to close the window. Start by creating a WPF project that target's the latest framework and add classes for DelegateCommand, MainViewModel and ViewModelBase inside a ViewModels folder. See below project setup.
How To Close A Window Via Click Command Using MVVM In WPF
Add the code for ViewModelBase class that implements the INotifyPropertyChanged interface.
public class clsViewModelBase : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
}
Next is to add the functionality of the DelegateCommand class that implements the ICommand interface. This class handles the Commands bound to the WPF controls
public class DelegateCommand : ICommand
{
    private readonly Predicate<object> _canExecute;
    private readonly Action<object> _execute;
    public event EventHandler CanExecuteChanged;

    public DelegateCommand(Action<object> execute) : this(execute, null)
    {
    }

    public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        if (_canExecute == null)
            return true;

        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    public void RaiseCanExecuteChanged()
    {
        if (CanExecuteChanged != null)
            CanExecuteChanged(this, EventArgs.Empty);
    }
}
For the Main Window View Model, create ClosingWindowCommand property that returns a Delegate command referencing a function to close the Window object. Note that we need to cast the object explicitly into a Window object.
 public partial class MainWindowViewModel : clsViewModelBase
 {
     private ICommand pClosingWindowCommand;
     public ICommand ClosingWindowCommand
     {
         get
         {
             return pClosingWindowCommand ?? (pClosingWindowCommand = new DelegateCommand(fnCloseWindow));
         }
     }

     public void fnCloseWindow(object obj)
     {
         Window window = (Window)obj;
         window.Close();
     }
 }
In our MainWindow.xaml, we need to reference the ViewModel namespace for us to have access to the ViewModel class. Next is to create a Window.DataContext element that calls the MainWindowViewModel class. In our Exit menu, Bind the ClosingWindowCommand to the Menu Item's Command property. Using this approach, when the user clicks on the Exit menu, the window unloads.
<Window x:Class="WPFCloseWindowUsingMVVM.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPFCloseWindowUsingMVVM"
        xmlns:localVM="clr-namespace:WPFCloseWindowUsingMVVM.ViewModels"
        mc:Ignorable="d"
        x:Name="MainProjectWindow"
        WindowStartupLocation="CenterScreen"
        Title="Close Window Using MVVM" Height="450" Width="800">
    <Window.DataContext>
        <localVM:MainWindowViewModel x:Name="vmLocalViewModel" />
    </Window.DataContext>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="25" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <Menu Grid.Row="0">
            <MenuItem Header="File" HorizontalAlignment="Left">
                <MenuItem Header="Exit" Command="{Binding ClosingWindowCommand}" CommandParameter="{Binding ElementName=MainProjectWindow}" HorizontalAlignment="Right"></MenuItem>
            </MenuItem>
        </Menu>
    </Grid>
</Window>
Output
How To Close A Window Via Click Command Using MVVM In WPF


Cheers!

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.