How to bind the WindowState property of a window in WPF using MVVM

Step 1: Create a new WPF project

windowstate1

Step 2: Create the ViewModel classes

Add the ViewModel classes that are used to do the bindings with the User Interface components

MainWindowViewModel.cs

This includes the WindowState property and setting this state to maximized upon construction:

namespace WindowState
{
    public class MainWindowViewModel : ViewModelBase
    {
        private System.Windows.WindowState _windowState;

        public MainWindowViewModel()
        {
            WindowState = System.Windows.WindowState.Maximized;
        }

        public System.Windows.WindowState WindowState
        {
            get { return _windowState; }
            set
            {
                _windowState = value;
                OnPropertyChanged("WindowState");
            }
        }
    }
}

ViewModelBase.cs

using System.ComponentModel;

namespace WindowState
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            var handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

Step 3: Update the MainWindow.xaml – add the DataContent

<Window x:Class="WindowState.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:WindowState"
        mc:Ignorable="d"
        WindowState="{Binding WindowState, Mode=TwoWay}"
        Title="MainWindow" Height="350" Width="525">

    <Window.DataContext>
        <local:MainWindowViewModel />
    </Window.DataContext>
    
    <Grid>        
    </Grid>
</Window>

So that on building and running the project, the window is set to the ‘maximized’ state:

windowstate2

Leave a Reply