Thursday, May 2, 2013

WPF Input Validation Using MVVM

Data validation is a key part in WPF.

Validation is used to alert the user that the data he entered is illegal.

In this post we will see how to Validate user input using MVVM binding.

I have created 2 different templates for input validation :

Click WPFInputValidation Link To Download full source.

Example 1 :

To impelment validation we need to use IDataErrorInfo interface.

IDataErrorInfo  interface provides the functionality to offer custom error information that a user  interface can bind to.

It has 2 Properties :

- Error : Gets an error message indicating what is wrong with this object.

- string this[string columnName] Indexer : it will return the error message for the property. The default is an empty string ("")


Let's go through step by step to understand validation with mvvm binding and styling the validation template.

Step 1 :  First change ErrorToolTip style by customizing the Template.



 
<ControlTemplate x:Key="ErrorToolTipTemplate_1">
 <ControlTemplate.Resources>
  <Style x:Key="textblockErrorTooltip" TargetType="TextBlock">
   <Setter Property="HorizontalAlignment" Value="Center" />
   <Setter Property="VerticalAlignment" Value="Center" />
   <Setter Property="FontWeight" Value="Bold" />
   <Setter Property="Foreground" Value="White" />
   <Setter Property="Margin" Value="10 0 10 0" />
  </Style>
 </ControlTemplate.Resources>
 <DockPanel LastChildFill="true">
  <Border Height="Auto"
   Margin="5,0,0,0"
   Background="#DC000C"
   CornerRadius="3"
   DockPanel.Dock="right">
    <TextBlock Style="{StaticResource textblockErrorTooltip}" 
Text="{Binding ElementName=customAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}" />
  </Border>
  <AdornedElementPlaceholder Name="customAdorner">
   <Border BorderBrush="#DC000C" BorderThickness="1.3" />
  </AdornedElementPlaceholder>
 </DockPanel>
</ControlTemplate> 
 


As shown in above source, created ControlTemplate and changed the error tooltip style by Adding Border control in DockPanel, within Border TextBlock placed with Text property binded to the error message set to the property from viewmodel.
 changed Backgroud of the border to Red so it will display error message surround with  border fill with red color. This will dispaly error on right side of the TextBox control. like :



ErrorTemplate uses adorner layer. which is drawing layer, using adorner layer you can add visual appearance to indicate an error without replacing controltemplate.

AdornedElementPlaceholder is part of the Validation feature of data binding. it specify where a decorated control is placed relative to other elements  in the ControlTemplate.

Step 2 : Create TextBox style and set Validation ErrorTemplate.


<Style TargetType="TextBox">
 <Setter Property="HorizontalAlignment" Value="Left" />
 <Setter Property="VerticalAlignment" Value="Top" />
 <Setter Property="Width" Value="150" />
 <Setter Property="Height" Value="30" />
 <Setter Property="Validation.ErrorTemplate" 
                 Value="{DynamicResource ErrorToolTipTemplate_1}" />
 <Style.Triggers>
  <Trigger Property="Validation.HasError" Value="true">
   <Setter Property="ToolTip" 
Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
  </Trigger>
 </Style.Triggers>
</Style> 


Created style of TargetType=TextBox, and Validation.ErrorTemplate is set to previously created template (DynamicResource ErrorToolTipTemplate)

you have to set Resource using DynamicResource, if your temaplate/style is available at global place (App.xaml)
if your control style and template is created in page itself then set resource using StaticResource keyword.

Step 3 : Create ViewModel class, that contains Properties to Bind into view.


public class InputValidationViewModel : ViewModelBase
{
 public InputValidationViewModel()
 {   
 }
 private string employeeName;
 public string EmployeeName
 {
  get { return employeeName; }
  set { employeeName = value; RaisePropertyChanged("EmployeeName"); }
 }
 private string email;
 public string Email
 {
  get { return email; }
  set {email = value; RaisePropertyChanged("Email"); }
 }
 private long phoneNumber;
 public long PhoneNumber
 {
  get { return phoneNumber; }
  set { phoneNumber = value; RaisePropertyChanged("PhoneNumber"); }
 }
 private bool IsValidEmailAddress
 {
  get { return emailRegex.IsMatch(Email); }
 }
} 
 

as shown in above code, ViewModel created and added some propeties that need to bind in UserControl.

Step 4 : Implement IDataErrorInfo Interface


 
public class InputValidationViewModel : ViewModelBase, IDataErrorInfo
{
 private Regex emailRegex = new Regex(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$");  
 public InputValidationViewModel()
 {   
 }
 
        private string error = string.Empty;
 public string Error
 {
  get { return error; }
 }
 public string this[string columnName]
 {
    get
    {
  error = string.Empty;
  if (columnName == "EmployeeName" && string.IsNullOrWhiteSpace(EmployeeName))
  {
   error = "Employee name is required!";
  }
  else if (columnName == "PhoneNumber" && PhoneNumber == 0)
  {
   error = "Phone number is required!";
  }
  else if (columnName == "PhoneNumber" && PhoneNumber.ToString().Length > 10)
  {
   error = "Phone number must have less than or equal to 10 digits!";
  }
  else if (columnName == "Email" && string.IsNullOrWhiteSpace(Email))
  {
   error = "Email address is required!";
  }
  else if (columnName == "Email" && !IsValidEmailAddress)
  {
   error = "Please enter valid email address!";
  }
  return error;

      }
       }
} 

IDataErrorInfo has Error property which returns the validation error that does not match the codition.

in above code, i set the error for each propeties by checking the codition, it coditiion is false then set the error for that property.

For valid email validation, created Regex expression to check entered email address is valid ro not.

This error appear on right side of the control that has property binded.

Step 5 : Last, Add TextBox cotrol in View


 
<TextBox Grid.Row="1"
 Grid.Column="1"
 Text="{Binding EmployeeName,
           Mode=TwoWay,
           UpdateSourceTrigger=PropertyChanged,
    ValidatesOnDataErrors=True}" /> 
 
  

Here EmployeeName proeprty is binded to TextBox control, you have to set ValidatesOnDataErrors=True to throw data error ( entered data is valida or not.)

Mode=TwoWay will allow user to change property from UI as well update UI from ViewModel property.

UpdateSourceTrigger=PropertyChanged will notify changes  is updated as soon as the property changes.

If UpdateSourceTrigger is not set, then TextBox was not immediately sent back to the source. Instead, the source was updated only after focus was lost on the TextBox.

This behavior is controlled by a property on the binding called UpdateSourceTrigger.

Example 2 :


In this example, only ControlTemplate is chaned, other things like : ViewModels Property, Controls are same.



As shown in above image, tooltip style is changed, ! mark with red circle surrounded image is added on the errortemplate.

small triangle added on template, to show top right corner of the control if any data error exists.

below are the  template change compare to previous example template :

 
<Border x:Name="ValidationErrorElement"
 BorderBrush="#FFDB000C"
 BorderThickness="1.2"
 CornerRadius="1"
 ToolTip="{Binding ElementName=customAdorner,
 Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
 <Grid Width="12"
  Height="12"
  Margin="1,-4,-4,0"
  HorizontalAlignment="Right"
  VerticalAlignment="Top"
  Background="Transparent">
  <Path Margin="1,3,0,0"
        Data="M 1,0 L6,0 A 2,2 90 0 1 8,2 L8,7 z"
        Fill="#FFDC000C" />
  <Path Margin="1,3,0,0"
        Data="M 0,0 L2,0 L 8,6 L8,8"
        Fill="#ffffff" />
 </Grid>
</Border>
<Border Grid.Column="0"
 Width="15"
 Height="15"
 Margin="0 0 3 0"
 HorizontalAlignment="Right"
 VerticalAlignment="Center"
 Background="Red"
 CornerRadius="10"
 ToolTip="{Binding ElementName=customAdorner,
 Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
 <TextBlock HorizontalAlignment="center"
  VerticalAlignment="center"
  FontWeight="Bold"
  Foreground="white"
  Text="!" />
</Border> 
 
 

as shown in above code,

In First border, 2 shapes is created using path, this will create Triangle shape to disply on top right corner of the control.

To know more about how to draw shpaes using Path, Please refer Shapes & Drawing in WPF This Link

it will help you to create your custom shapes based on your requirement.

Second border will create red cirlce (by setting CornerRadius proeprty) with ! text wihin cirlce area.

it will display right side of the cotrol, if any data error is there for property.

Conclusion

This way you can create you custom error template for input controls.

Dwonload link

Friday, April 26, 2013

2D Animation in WPF

WPF providing great features for creating rich user interface using graphics, layouts and animations.

In this post we will discuss how to create Animations and types of Animations with examples.

Animation

Click WPFAnimations To Download source

animation is used, when you want your user interface more attractive like :

 -  moving control from one place to another
 - continuously change the color of the control on some time interval
 -  rotate control
 - change the opacity of control
 - resize control ( change size from small to large and large to small)

you cannot set animation directly to the control, instead WPF provides container (Storyboard) for the animation.

Storyboard is a container timeline that provides object and property targeting information for its child animations.

The Storyboard class provides the Storyboard.TargetName and Storyboard.TargetProperty attached properties. You set these properties on an animation to specify its target object and property.

There are 3 types of animations  available in WPF

1. DoubleAnimation
2. ColorAnimation
3. Double/Color Animation Using KeyFrame


1. DoubleAnimation

A DoubleAnimation creates a transition between two double values.

like change opacity 0 to 1, or change width/height of the control.

Example 1:

Below example describes Translate Visual Element from one postition to another postion using DoubleAnimation. ( see below images)







 <Rectangle x:Name="MyTranslateRectangle"
    Width="90"
 Height="35"
 Margin="10"
 HorizontalAlignment="Left"
 Fill="#AA0000FF"
 Stroke="#0000FF"
 StrokeThickness="1">
 <Rectangle.RenderTransform>
  <TranslateTransform X="0" Y="0" />
 </Rectangle.RenderTransform>
 <Rectangle.Triggers>
  <EventTrigger RoutedEvent="Loaded">
   <BeginStoryboard Storyboard="{StaticResource TranslateStoryboard}" />
  </EventTrigger>
 </Rectangle.Triggers>
</Rectangle> 
 
 
Created Rectangle control in page with setting some properties ( Fill,Stroke,Width,Height etc.)
added TranslateTransfrom to the Rectangle control within UIElement.RenderTrandform property.
 RenderTrandform is used to tranfrom UIElement from one coordniate to another one.
it will rotate, scale, move (translate) rendering position of FrameworkElements.


WPF provides the following  Transform classes :

RotateTransform : Rotates an element by the specified Angle.
ScaleTransform : Scales an element by the specified ScaleX and ScaleY amounts.
SkewTransform : Skews an element by the specified AngleX and AngleY amounts.
TranslateTransform : Moves (translates) an element by the specified X and Y amounts.

we have used to TranslateTransform for move Rectangle from one postition to another using storyboard.
 
 
<Storyboard x:Key="TranslateStoryboard" RepeatBehavior="Forever">
 <DoubleAnimation Duration="0:0:01"
  From="0"
  Storyboard.TargetName="MyTranslateRectangle"
  Storyboard.TargetProperty="(Rectangle.RenderTransform).(TranslateTransform.X)"
  To="350" />
</Storyboard> 


Now, create storyboard with DoubleAnimation and set TargetName to the name of Rectangle, set the TargetProperty to the TranslateTransform.X, set To=350 to move Rectangle from 0 to 350 in X coordinate ( Horizontal Direction - from Left to Right).

Now, BeginStoryboard on Loaded event of Rectangle, it will start storyboard with applied doubleanimation.

if you want animation continue after complete the cycle , set Storayboard RepeatBehavior property to Forever.

Example 2 :

Below examples describes changing Width property of UIElement.





<Ellipse Name="MyEllipse"
 Width="50"
 Height="50"
 Margin="10"
 VerticalAlignment="Top"
 Fill="#28B7ED"
 Stroke="Gray"
 StrokeThickness="2">
 <Ellipse.Triggers>
  <EventTrigger RoutedEvent="Loaded">
  <BeginStoryboard>
   <Storyboard RepeatBehavior="Forever">
    <DoubleAnimation BeginTime="0:0:0"
     Duration="0:0:1"
     From="50"
     Storyboard.TargetName="MyEllipse"
     Storyboard.TargetProperty="Width"
     To="350" />
    <DoubleAnimation BeginTime="0:0:1"
     Duration="0:0:1"
     From="350"
     Storyboard.TargetName="MyEllipse"
     Storyboard.TargetProperty="Width"
     To="50" />
   </Storyboard>
  </BeginStoryboard>
  </EventTrigger>
 </Ellipse.Triggers>
</Ellipse>

Created Ellipse with 2 DoubleAnimation added one for change width proerty from 50 to 350 and one for change width property from 350 to 50 and place both animations within Storyboard.

Example 3 :

Below example describes Rotate Image on 360 angle wihtin specified area.



<Image Grid.Column="1"
 Width="160"
 Height="160"
 Margin="10"
 HorizontalAlignment="Left"
 Cursor="Hand"
 Source="/WPFAnimations;component/Images/1.png"
 Stretch="Fill">
 <Image.RenderTransform>
  <RotateTransform x:Name="TransRotate" CenterX="80" CenterY="80" />
 </Image.RenderTransform>
 <Image.Triggers>
  <EventTrigger RoutedEvent="Image.Loaded">
  <BeginStoryboard>
   <Storyboard TargetProperty="Angle">
    <DoubleAnimation AutoReverse="False"
     By="360"
     Duration="0:0:0.7"
     RepeatBehavior="Forever"
     Storyboard.TargetName="TransRotate"
     Storyboard.TargetProperty="Angle" />
   </Storyboard>
  </BeginStoryboard>
  </EventTrigger>
 </Image.Triggers>
</Image>

to rotare image RotateTransform is used, it has CenterX & CenterY proeprty to set Image on X,Y posttion in area, Angle property is used to RotateImage on Specified Angle (degree).

You can also create Animation from C# (code behind) instead of XAML. like :

DoubleAnimation dblaSlideUp = new DoubleAnimation();
dblaSlideUp.To = 80;
dblaSlideUp.Duration = new Duration(TimeSpan.FromSeconds(.5));
Storyboard.SetTargetName(dblaSlideUp, EnergyGrid.Name);
Storyboard.SetTargetProperty(dblaSlideUp, new PropertyPath(Border.HeightProperty));
Storyboard strbSlideUp = new Storyboard();
strbSlideUp.Children.Add(dblaSlideUp);
strbSlideUp.Begin(this);
BottomTextBox.Text = "Click to Maximize";

this will change Height of the UIElement with Duration of 5 seconds.

2. ColorAnimation

used to animates the value of a Color property between two target values using linear interpolation over a specified Duration.

 Example 1 :

Below example describes change the color value of UIElement.

 
 

<Storyboard x:Key="HighlightStoryboard"
 BeginTime="00:00:00"
 RepeatBehavior="Forever"
 Storyboard.TargetName="txtBlockScannerText"
 Storyboard.TargetProperty="(Foreground).(SolidColorBrush.Color)">
 <ColorAnimation Duration="0:0:1"
  From="GreenYellow"
  To="Magenta" />
</Storyboard>

Created Storyboard with ColorAnimation by setting TargetProperty to Foreground color of the control.

<TextBlock x:Name="txtBlockScannerText"
 HorizontalAlignment="Center"
 VerticalAlignment="Center"
 Text="This is Highlighted Text">
 <TextBlock.Triggers>
  <EventTrigger RoutedEvent="Loaded">
   <BeginStoryboard Storyboard="{StaticResource HighlightStoryboard}" />
  </EventTrigger>
 </TextBlock.Triggers>
</TextBlock>

Created TextBlock control, added Loaded EventTrigger with setting previously created Storybaord Resource.

3. ColorAnimationUsingKeyFrames

 Animates the value of a Color property along a set of KeyFrames over a specified Duration.

A key frame animation's target values are defined by its KeyFrames property, which contains a collection of ColorKeyFrame objects. Each ColorKeyFrame defines a segment of the animation with its own target Value and KeyTime.

KeyTime will sets the time at which the key frame's target Value should be reached.

Unlike a ColorAnimation, a ColorAnimationUsingKeyFrames can have more than two of target values.

Example :









<Border x:Name="MyBorder"
 Grid.Row="4"
 Width="500"
 Height="40"
 BorderBrush="Black"
 BorderThickness="1">
 <Border.Background>
  <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
   <GradientStop Offset="0" Color="#DEB40A" />
   <GradientStop Offset="1" Color="#FF7F00" />
  </LinearGradientBrush>
 </Border.Background>
 <Border.Triggers>
 <EventTrigger RoutedEvent="MouseEnter">
  <BeginStoryboard>
  <Storyboard>
   <ColorAnimationUsingKeyFrames Storyboard.TargetName="MyBorder" 
                           Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
    <LinearColorKeyFrame KeyTime="0:0:0.5" Value="Magenta" />
    <DiscreteColorKeyFrame KeyTime="0:0:0.8" Value="Black" />
   </ColorAnimationUsingKeyFrames>
  </Storyboard>
  </BeginStoryboard>
 </EventTrigger>
 <EventTrigger RoutedEvent="MouseLeave">
  <BeginStoryboard>
  <Storyboard>
   <ColorAnimationUsingKeyFrames Storyboard.TargetName="MyBorder" 
                           Storyboard.TargetProperty="(Panel.Background).(GradientBrush.GradientStops)[1].(GradientStop.Color)">
    <EasingColorKeyFrame KeyTime="0:0:1" Value="#FF7F00" />
   </ColorAnimationUsingKeyFrames>
  </Storyboard>
 </BeginStoryboard>
 </EventTrigger>
 </Border.Triggers>
</Border>
 
 
In above code, 2 KeyFrame classes used with ColorAnimationUsingKeyFrames animation.
- LinearColorKeyFrame is used to change the color smoothly.
- DiscreteColorKeyFrame will change color quickly within specified KeyTime.
 
when user moves mouse over to the border control, 
color of the last GradientStop will change to Magenta within half second, then quickly change to Black.
 
when user leave mouse from border, the last GradientStop color again set to Default color.
 
So, this way you can create Animation and apply to any UIElement as per you project requirement, 
In this post, i tried to simplify examples with piece of code that will helpful to create 2D animation.