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...

How to edit selected row of DataGrid and add the new row to DataGrid

MainWindow.xaml

<Window x:Class="WpfEx.Views.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:WpfEx"
       mc:Ignorable="d">
  <StackPanel>

<DataGrid ItemsSource="{Binding LstStudents}" SelectedItem="{Binding SelectedStudent}" AutoGenerateColumns="False" Height="200" Width="200" HorizontalAlignment="Left">
           <DataGrid.Columns>
               <DataGridTextColumn Header="Name" Binding="{Binding Name}"/>
               <DataGridTextColumn Header="Roll" Binding="{Binding Roll}"/>
           </DataGrid.Columns>
       </DataGrid>
       <Button Content="Edit Selected row" Command="{Binding EditSelectedRowCommand}" HorizontalAlignment="Left" Width="150"/>
       <Button Content="Add row" Command="{Binding AddRowCommand}" HorizontalAlignment="Left" Width="150"/>
</StackPanel>
</Window>

MainWindow.xaml.cs

 public partial class MainWindow : Window
   {
     
       public MainWindow()
       {
           InitializeComponent();
             DataContext= new MainWindowViewModel(); 
       }

   }

MainWindowViewModel.cs

 public class MainWindowViewModel : BindableBase
   {
       public MainWindowViewModel()
       {
           EditSelectedRowCommand = new DelegateCommand(EditRow);
           AddRowCommand = new DelegateCommand(AddRow);

    LstStudents =new ObservableCollection<Student>
           {
               new Student
               {
                   Name="ABC",
                   Roll=1
               },
               new Student
               {
                   Name="DEF",
                   Roll=2
               }
           };         
       }

       private void AddRow()
       {
           var studentToAdd = new Student();
           var addWindow = new Add(studentToAdd);
         
           var window = new Window
           {
               Title = "Add Student",
               Content = addWindow
           };

           addWindow.AddStudent.Click += (s, e) =>
     {
      LstStudents.Add(studentToAdd);
     window.Close();
    };
   
           window.Show();
       }

       private void EditRow()
       {
    var editWindow = new Window
           {
               Title="Edit Selected Student",
               Content = new Edit(SelectedStudent)
           };
           editWindow.Show();
       }

       private ObservableCollection<Student> _lstStudents =
    new ObservableCollection<Student>();

       public ObservableCollection<Student> LstStudents
       {
           get { return _lstStudents; }
           set { SetProperty(ref _lstStudents, value); }
       }

       private Student _selectedStudent=new Student();

       public Student SelectedStudent
       {
           get { return _selectedStudent; }
           set { SetProperty(ref _selectedStudent ,value); }
       }

       public ICommand EditSelectedRowCommand { get; set; }
       public ICommand AddRowCommand { get; set; }

}

Student.cs

public partial class Student
   {

       public int Roll { get; set; }
       public string Name { get; set; }
   }

Add.xaml

<UserControl x:Class=" WpfEx.Views.Add"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:local="clr-namespace: WpfEx.Views"
            mc:Ignorable="d" >
   <Grid>
       <Grid.RowDefinitions>
           <RowDefinition Height="40"/>
           <RowDefinition Height="40"/>
           <RowDefinition Height="40"/>
       </Grid.RowDefinitions>
       <Grid.ColumnDefinitions>
           <ColumnDefinition Width="100"/>
           <ColumnDefinition Width="*"/>
       </Grid.ColumnDefinitions>
       <TextBlock Text="Name : "/>
       <TextBox Width="200" Text="{Binding Name}" Grid.Column="1" Margin="5" HorizontalAlignment="Left"/>
     
       <TextBlock Text="Roll : " Grid.Row="1"/>
       <TextBox Width="200" Text="{Binding Roll}"  Grid.Column="1" Grid.Row="1" Margin="5"  HorizontalAlignment="Left"/>
       <Button Content="Add" x:Name="AddStudent" Grid.Column="1" Grid.Row="2" HorizontalAlignment="Right" x:FieldModifier="public" Margin="5" Width="150"/>

   </Grid>
</UserControl>

Add.xaml.cs

public partial class Add : UserControl
   {
       public Add(Student student)
       {
           InitializeComponent();
           DataContext = student;
       }
   }

Edit.xaml

<UserControl x:Class=" WpfEx.Views.Edit"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:local="clr-namespace: WpfEx.Views"
            mc:Ignorable="d"
            d:DesignHeight="450" d:DesignWidth="800">
   <Grid>
       <Grid.RowDefinitions>
           <RowDefinition Height="40"/>
           <RowDefinition Height="40"/>
       </Grid.RowDefinitions>
       <Grid.ColumnDefinitions>
           <ColumnDefinition Width="100"/>
           <ColumnDefinition Width="*"/>
       </Grid.ColumnDefinitions>
       <TextBlock Text="Name : "/>
       <TextBox Width="200" Text="{Binding Name}" Grid.Column="1" Margin="5" HorizontalAlignment="Left"/>
     
       <TextBlock Text="Roll : " Grid.Row="1"/>
       <TextBox Width="200" Text="{Binding Roll}"  Grid.Column="1" Grid.Row="1" Margin="5"  HorizontalAlignment="Left"/>
   </Grid>
</UserControl>

Edit.xaml.cs

public partial class Edit : UserControl
   {
       public Edit(Student student)
       {
           InitializeComponent();
           DataContext = student;
       }
   }

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