Understanding Commands in WPF: A Cleaner Alternative to Button Click Events

Many WPF developers start by using Button Click events for handling user actions. At first, this seems simple and straightforward. But very soon, the code-behind file becomes huge , and maintaining it turns into a challenge. One big problem arises: when the logic changes, the button does not enable or disable automatically , and testing button click logic becomes very difficult. So the big question is: Is there a better way to handle button actions in WPF? The answer is Commands . In this post, we’ll learn how to use Commands in WPF with a simple, practical example. We’ll cover: What a Command is How it works Why using Commands is better than Click events How buttons can automatically enable or disable based on conditions What is a Command in WPF? In WPF, a Command acts as a middle layer between the UI and your logic. Instead of the button directly calling a method, it triggers a Command , and the Command decides: What code should run Whether the button s...

Multiple ways to handle Checked/Unchecked event in wpf using MVVM

In this post i am trying to explain multiple way to handle Checked/Unchecked event in wpf using MVVM

First let's create a view which contains multiple CheckBox. 

All CheckBox will handle the Checked/Unchecked event differently. 


CheckBoxEx.xaml


<Window x:Class="PrismApp.Views.CheckBoxEx"

             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

             xmlns:prism="http://prismlibrary.com/"

             prism:ViewModelLocator.AutoWireViewModel="True">

    <StackPanel >

        <CheckBox Content="Bind Command by passing CheckBox as CommandParameter but set command parameter type is object" HorizontalAlignment="Left" VerticalAlignment="Center"  Name="chkObj"

                  Command="{Binding CheckedChangedCommand}" CommandParameter="{Binding ElementName=chkObj}"/>

        <CheckBox Content="Bind Command by passing CheckBox as CommandParameter" HorizontalAlignment="Left" VerticalAlignment="Center"  Name="chk"

                  Command="{Binding CheckedByCheckBoxCommand}" CommandParameter="{Binding ElementName=chk}"/>

        <CheckBox Content="Bind Command by passing CheckBox IsChecked property as CommandParameter" HorizontalAlignment="Left" VerticalAlignment="Center"  Name="chkbx"

                  Command="{Binding CheckedByIsCheckedPropertyCommand}" CommandParameter="{Binding ElementName=chkbx,Path=IsChecked}"/>

        <CheckBox Content="Bind Command by passing DataContext as CommandParameter" HorizontalAlignment="Left" VerticalAlignment="Center"

                  Command="{Binding CheckedByDataContextCommand}" IsChecked="{Binding IsVmChecked}" CommandParameter="{Binding}"/>

        <CheckBox Content="By Binding IsChecked property of CheckBox with VM property" HorizontalAlignment="Left" VerticalAlignment="Center"

                 IsChecked="{Binding IsChecked}" />

    </StackPanel>

</Window>


CheckBoxEx.xaml.cs


    public partial class CheckBoxEx : Window

    {

        public CheckBoxEx()

        {

            InitializeComponent();

        }

    }



CheckBoxExViewModel.cs


using Prism.Commands;

using Prism.Mvvm;

using System.Windows.Controls;

using System.Windows;


    public class CheckBoxExViewModel : BindableBase

    {

        public CheckBoxExViewModel()

        {


        }


        #region 5 ways to handle the Checked/UnChecked of CheckBox using Command


        #region Way 1: When command parameter type is object need to cast

        private DelegateCommand<object> _checkedChangedCommand;

        public DelegateCommand<object> CheckedChangedCommand => (_checkedChangedCommand = new DelegateCommand<object>(CheckChanged));


        private void CheckChanged(object obj)

        {

            var chekbox = obj as CheckBox;

            MessageBox.Show($"Checkbox is checked (Bind Command by passing CheckBox as CommandParameter but set command parameter type is object) :{chekbox.IsChecked}");


        }

        #endregion


        #region Way 2: When command parameter type is CheckBox no need to cast

        private DelegateCommand<CheckBox> _checkedByCheckBoxCommand;

        public DelegateCommand<CheckBox> CheckedByCheckBoxCommand => (_checkedByCheckBoxCommand = new DelegateCommand<CheckBox>(CheckedByCheckBoxChanged));


        private void CheckedByCheckBoxChanged(CheckBox chekbox)

        {

            MessageBox.Show($"Checkbox is checked (Bind Command by passing CheckBox as CommandParameter) :{chekbox.IsChecked}");


        }

        #endregion


        #region Way 3:When command parameter type is CheckBox IsChecked property type

        private DelegateCommand<bool?> _checkedByIsCheckedPropertyCommand;

        public DelegateCommand<bool?> CheckedByIsCheckedPropertyCommand => (_checkedByIsCheckedPropertyCommand = new DelegateCommand<bool?>(CheckedByIsCheckedPropertyChange));

        private void CheckedByIsCheckedPropertyChange(bool? isChecked)

        {

            MessageBox.Show($"Checkbox is checked (Bind Command by passing CheckBox IsChecked property as CommandParameter):{isChecked}");


        }

        #endregion


        #region Way 4:When command parameter type is DataContext

        private bool _isVmChecked;


        public bool IsVmChecked

        {

            get { return _isVmChecked; }

            set

            {

                SetProperty(ref _isVmChecked, value);

            }

        }

        private DelegateCommand<CheckBoxExViewModel> _checkedByDataContextCommand;

        public DelegateCommand<CheckBoxExViewModel> CheckedByDataContextCommand => (_checkedByDataContextCommand = new DelegateCommand<CheckBoxExViewModel>(CheckedByDataContextChange));

        private void CheckedByDataContextChange(CheckBoxExViewModel datacontext)

        {

            MessageBox.Show($"Checkbox is checked (Bind Command by passing DataContext as CommandParameter):{datacontext.IsChecked}");


        }

        #endregion


        #region Way 5: By Binding IsChecked property of CheckBox

        private bool _isChecked;


        public bool IsChecked

        {

            get { return _isChecked; }

            set

            {

                SetProperty(ref _isChecked, value);

                MessageBox.Show($"Checkbox is checked (By Binding IsChecked property of CheckBox):{_isChecked}");

            }

        }

        #endregion


        #endregion

    }


Note: Way 1 and Way 2 are not recommended to use because we should not use any Views components in ViewModel.

Comments

Popular posts from this blog

Filter DataGrid and ListView in wpf using ICollectionView

Pagination of DataGrid in WPF using MVVM

How to Create TabControl using Prism Region