b

Wednesday, 26 December 2012

Data Annotations in WPF C#

data annotations in wpf


Step1) Create WPF Project
Step2) Add 3 TextBoxes
  • Username
  • Password
  • Email

Step 3)  Add a custom class  called Profile
   
  public class Profile
    {
        [Required(ErrorMessage = "user name required", AllowEmptyStrings=false)]
        public String username { get; set; }
        [Required(ErrorMessage = "password required")]
        public String password { get; set; }
        [Required(ErrorMessage = "email required")]
        public String email { get; set; }
    }


Step 4) Bind these class  properties to TextBoxes in XAML.

<Page
      xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"
      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"
      mc:Ignorable="d"
      d:DesignHeight="400" d:DesignWidth="600" x:Class="Wpfone.ValidationPage"
     xmlns:local="clr-namespace:Wpfone"
    Title="ValidationPage" >
    <Page.Resources>
        <local:Profile x:Key="myprofile"></local:Profile>
    </Page.Resources>
    <Page.DataContext>
        <Binding  Source="{ StaticResource myprofile}"></Binding>
    </Page.DataContext>
    <Canvas x:Name="canvas1" HorizontalAlignment="Left" Height="400" VerticalAlignment="Top" Width="700">
        <TextBlock TextWrapping="Wrap" Text="Validating Controls in WPF/Validations in WPF" FontSize="30px"/>
        <Label Content="UserName:" Canvas.Left="10" Canvas.Top="49" Width="103"/>
        <TextBox TextWrapping="Wrap" x:Name="txtUsername" Text="{Binding Path=username}" Canvas.Left="130" Canvas.Top="54" Height="21" Width="242">
        </TextBox>
        <Label Content="Password:" Canvas.Left="10" Canvas.Top="87" Width="103"/>
        <TextBox  TextWrapping="Wrap" x:Name="txtPassword"  Canvas.Left="130" Canvas.Top="92" Height="21" Width="242">
            <TextBox.Text>
                <Binding  Path="password" Source="{StaticResource myprofile}" 
                          NotifyOnValidationError="True" 
                          ValidatesOnExceptions="True"
                            BindsDirectlyToSource="True"
                          ></Binding>
            </TextBox.Text>
        </TextBox>
        <Label Content="Email:" Canvas.Left="10" Canvas.Top="125" Width="103"/>
        <TextBox TextWrapping="Wrap" x:Name="txtEmail" Text="{Binding Path=email}" Canvas.Left="130" Canvas.Top="130" Height="21" Width="242">
        </TextBox>
        <Button  x:Name="btnSubmit" Content="Submit" Width="106" Canvas.Left="38" Canvas.Top="183" Height="23" Click="btnSubmit_Click"/>
        <CheckBox Content="CheckBox"/>

    </Canvas>


</Page>

Step 5) in The Button Event Handler
 private void btnSubmit_Click(object sender, RoutedEventArgs e)
{
           this.InvalidateArrange();
            Profile p=(Profile)this.DataContext;
            ValidationContext context = new ValidationContext(p, serviceProvider:null,items:null);
           var list = new List<System.ComponentModel.DataAnnotations.ValidationResult>();
           bool b= Validator.TryValidateObject(p, context, list, true);
           if (b) MessageBox.Show("Validation success");
           else
           {
               String strErr=String.Empty;
               foreach (System.ComponentModel.DataAnnotations.ValidationResult errResult in list)
               {
                   strErr += errResult.ErrorMessage;
               }
               MessageBox.Show(strErr);
           }
}

Output


Tags:data annotations in wpf, data annotations validator , validations in WPF, field validations in WPF, data validations in WPF,Validations in WPF textbox,UI validations in WPF.

















No comments:

Post a Comment