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

Validation By ValidationRule in Wpf using MVVM

View

<Window x:Class="WpfPrismTutorial.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:WpfPrismTutorial"
        mc:Ignorable="d"
        prism:ViewModelLocator.AutoWireViewModel="True"
        xmlns:prism="http://prismlibrary.com/"
        xmlns:valid="clr-namespace:WpfPrismTutorial.Validations"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <ControlTemplate x:Key="errorTemplate">
            <StackPanel Orientation="Horizontal">
            <AdornedElementPlaceholder x:Name="ErrorHolder" >
                <Border BorderBrush="red" BorderThickness="1" />
            </AdornedElementPlaceholder>
            <TextBlock  Text="{Binding [0].ErrorContent}" VerticalAlignment="Center" HorizontalAlignment="Right" Foreground="Red"/>
        </StackPanel>

        </ControlTemplate>
    </Window.Resources>
    <Grid VerticalAlignment="Center" HorizontalAlignment="Left">
    <StackPanel Orientation="Horizontal" Grid.Row="2">
            <TextBlock Text="Validation by ValidationRule" Margin="5,5"/>
            <TextBox Height="30" Width="300" Validation.ErrorTemplate="{StaticResource errorTemplate}">
                <TextBox.Text>
                    <Binding Path="MainWindowModel.ValidationByValidationRule" ValidatesOnDataErrors="True" UpdateSourceTrigger="PropertyChanged">
                        <Binding.ValidationRules>
                            <valid:Validator/>
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
            </TextBox>
         
        </StackPanel>
     
    </Grid>
</Window>

ViewModel

public class MainWindowViewModel : BindableBase
    {
        private MainWindowModel mainWindowModel = new MainWindowModel();

        public MainWindowModel MainWindowModel
        {
            get { return mainWindowModel; }
            set { SetProperty(ref mainWindowModel, value); }
        }
    }

Model

 public class MainWindowModel : BindableBase
    {
        #region Validation By ValidationRule

        private string _validationByValidationRule = string.Empty;

        public string ValidationByValidationRule
        {
            get { return _validationByValidationRule; }
            set
            {
                SetProperty(ref _validationByValidationRule, value);
            }
        }
        #endregion
    }

 class Validator : ValidationRule
 {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
             if (string.IsNullOrEmpty(value?.ToString()))
                   return new ValidationResult(false, "Validation By ValidationRule should not empty");
            return new ValidationResult(true, null);
        }
    }

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