Thursday, 31 October 2013

WPF VALIDATION - MANOHAR GOUD 9866550012



WPF validation


There are too many ways to validate the WPF controlls. I explain here some of them with example. 
We need a validation to prevent user from entering a wrong details.
Here we used IDataErrorInfo for validation.Validation made easy with IDataErrorInfo. here I explain you how we used IDataErrorInfo in WPF for validating the controlls. If we are using binding property to bind the contrlss with the properties then IDataErrorInfo is a very easy to use.I go through with most of the post but they not provide the combobox validation but here I explain the combobox validation also
First we need to create a class with some properties to test and list for binding the comboboxes

We create a class "Student" which inherit with IDataErrorInfo 
class Student : IDataErrorInfo
    {
        public string FirstName { get; set; }
        public int RollNumber { get; set; }
        public string Division { get; set; }

        public List<string> Divisions { get; set; }

        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get
            {
                string result = null;
                if (columnName == "FirstName")
                {
                    if (string.IsNullOrEmpty(FirstName) || FirstName.Length < 3)
                        result = "Please enter a Name";
                }
                if (columnName == "RollNumber")
                {
                    if (RollNumber <= 0)
                        result = "Please enter a Proper roll Number";
                }
                if (columnName == "Division")
                {
                    if (string.IsNullOrEmpty(Division))
                        result = "Please select Division";
                }
                return result;
            }
        }
    }


.xaml code

     <Window.Resources>
        <Style TargetType="{x:Type TextBox}">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Margin" Value="0,2,40,2" />
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">
                            <Border Background="OrangeRed" DockPanel.Dock="right" Margin="5,0,0,0" 
                                Width="20" Height="20" CornerRadius="5"
                                ToolTip="{Binding ElementName=customAdorner, 
                                          Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                <TextBlock Text="?" VerticalAlignment="center" HorizontalAlignment="center" 
                                   FontWeight="Bold" Foreground="white" />
                            </Border>
                            <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                                <Border BorderBrush="red" BorderThickness="1" />
                            </AdornedElementPlaceholder>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
        <Style TargetType="{x:Type ComboBox}">
            <Setter Property="VerticalAlignment" Value="Center" />
            <Setter Property="Margin" Value="0,2,40,2" />
            <Setter Property="Validation.ErrorTemplate">
                <Setter.Value>
                    <ControlTemplate>
                        <DockPanel LastChildFill="True">
                            <Border Background="OrangeRed" DockPanel.Dock="right" Margin="5,0,0,0" 
                                Width="20" Height="20" CornerRadius="5"
                                ToolTip="{Binding ElementName=customAdorner, 
                                          Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
                                <TextBlock Text="!" VerticalAlignment="center" HorizontalAlignment="center" 
                                   FontWeight="Bold" Foreground="white" />
                            </Border>
                            <AdornedElementPlaceholder Name="customAdorner" VerticalAlignment="Center" >
                                <Border BorderBrush="red" BorderThickness="1" />
                            </AdornedElementPlaceholder>
                        </DockPanel>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid x:Name="grdStudentData" Margin="0,20">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition Width="*" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <Grid.CommandBindings>
            <CommandBinding Command="New" CanExecute="Confirm_CanExecute" Executed="Confirm_Executed" />
        </Grid.CommandBindings>

        <Label Content="First Name:" Grid.Column="0" Grid.Row="0" />
        <Label Content="Division:" Grid.Column="0" Grid.Row="1" />
        <Label Content="Roll No:" Grid.Column="0" Grid.Row="2" />
        
        <TextBox x:Name="txtFirstName" Grid.Row="0" Grid.Column="1" 
             Validation.Error="Validation_Error"
             Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=FirstName,
                    ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />

        <ComboBox x:Name="cbpdepartment" Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Divisions,Mode=TwoWay}" Validation.Error="Validation_Error" SelectedItem="{Binding UpdateSourceTrigger=PropertyChanged, Path=Division,ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />

        <TextBox x:Name="txtRollNumber" Grid.Row="2" Grid.Column="1" 
             Validation.Error="Validation_Error"
             Text="{Binding UpdateSourceTrigger=PropertyChanged, Path=RollNumber,
                    ValidatesOnDataErrors=true, NotifyOnValidationError=true}" />
        
        <Button Content="Submit" Grid.ColumnSpan="2" Grid.Row="3" Grid.Column="1" Margin="0,0,10,0"
            HorizontalAlignment="right" VerticalAlignment="Center" Command="New"/>
    </Grid>


.xaml.cs code


      private int _errors = 0;
        private Student _student = new Student();
        public ValidationPart1()
        {
            InitializeComponent();
            _student.Divisions = new List<string>();
            _student.Divisions.Add(string.Empty);
            _student.Divisions.Add("Fifth");
            _student.Divisions.Add("Sixth");
            _student.Divisions.Add("Seventh");
            grdStudentData.DataContext = _student;
        }

        private void Confirm_CanExecute(object sender, CanExecuteRoutedEventArgs e)
        {
            e.CanExecute = _errors == 0;
            e.Handled = true;
        }

        private void Confirm_Executed(object sender, ExecutedRoutedEventArgs e)
        {
           //Insert logic of the page
        }

        private void Validation_Error(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action == ValidationErrorEventAction.Added)
                _errors++;
            else
                _errors--;
        }
        

Output
WPF Validation Example

No comments:

Post a Comment