Learn Important WPF (XAML) Concepts in 15 Minutes

Introduction

Nowadays there is a huge amount of resources available in the ocean of the internet. There is a thought that if there is too much of anything then that might cause confusion of what we are supposed to search for. Likewise there are many resources available to learn WPF, but I thought that there should be an article that explains the basics of WPF as shortly as possible so with that sprit I prepare this content that easily and quickly teaches WPF (XAML).

What are all the basic important concepts of WPF (XAML)?

There are several concepts of WPF, but the following are all the basic and important concepts of WPF:



Binding

Binding in XAML provides ultimate access to the definition interface that connects the properties of binding target objects and any data source typically binding elements may be a WPF element and the data source can be a database, an XML file, or any object that contains data.



Types of Binding

There are the following types that play a major role in bindings:

  • Data Binding
  • Element Binding
  • Resource Binding
  • Relative Binding
  • Template Binding

Binding Data Flow

Data can flow from Source to Target depending on the following Modes.

Modes

  • One Way
  • Two Way
  • One way to source


Data Binding

Data binding is the process that establishes a connection between the application UI and the business logic.

  • Typically, Binding requires four components
  • Target Object
  • Source Object
  • Target Property (Should be a DP, That supports default bindings)
  • Path Value

Declare Source Property

  1. public string MyText  
  2.         {  
  3.             get { return (string)GetValue(MyTextProperty); }  
  4.             set { SetValue(MyTextProperty, value); }  
  5.         }  
  6.   
  7.         // Using a DependencyProperty as the backing store for MyText.  This enables animation, styling, binding, etc...  
  8.         public static readonly DependencyProperty MyTextProperty =  
  9.             DependencyProperty.Register("MyText"typeof(string), typeof(TextBox), new PropertyMetadata("Tamil Valga! Tamil Valarga!!")); 

The following is an example of binding with the Target property:

  1. <TextBox Name="text1" Text="{Binding MyText}"/>     

The following is an example of setting the Data Context:

  1. this.DataContext = this






Element Binding

It is similar to Data Binding but the Source Object is actually a UI element. When binding, it requires an element and a Path if required.

The following is an example of binding a Target Element with a Source Element in XAML:

  1. <TextBox  Name="text1" Text="Tamil Valga! Tamil Valarga!!"/>  
  2. <TextBlock Text="{Binding Text, ElementName=text1}" Margin="134,169,135,117"/> 




Relative Binding

It gets or sets the binding source by specifying its location relative to the position of the binding target. The Binding.ElementName and Binding.Source properties also enable setting the source of the binding explicitly.

However, only one of the three properties, ElementName, Source and RelativeSource, should be set for each binding, or a conflict can occur.

  1. <Button Content="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=ActualWidth}"/> 




Template Binding


Template Binding is very optimized binding for template controls, analogous to a binding constructed with {Binding RelativeSource={RelativeSource TemplatedParent}}.

A TemplateBinding is always a one-way binding, even if the properties involved default to two-way binding. Both properties involved must be dependency properties.

  1. <Button Background="Orange">  
  2.     <Button.Template>  
  3.         <ControlTemplate>  
  4.             <Rectangle Fill="{TemplateBinding Background}"  Margin="0,0,0,-68"></Rectangle>  
  5.         </ControlTemplate>  
  6.     </Button.Template>  
  7. </Button> 




Resources

Whenever an object needs to be reused in various places in an application we use resources for it. A resource can be classified as one of various types. These resources are primarily two types of resources: XAML resources and resource data files. Examples of XAML resources include brushes and styles. Resource data files are non-executable data files that an application needs. Also called as follows:

  • Static Resource
  • Dynamic Resources.

Static Resources

<object property="{StaticResource key}" .../>

  1. <object property="{StaticResource key}" .../>  
  2.   
  3.   
  4. <object>  
  5.     <object.property>  
  6.         <StaticResource ResourceKey="key" .../>  
  7.     </object.property>  
  8. </object> 
  • It assigns the property in the while between compilation and when the application runs. So all the values are resolved before the application runs
  • It will be assigned once at the compile time, so the value changes are done after the runtime can be ignored
  • It uses the same value up to the entire lifetime of the application
  • It is very optimal to use it whenever the value may not be changed, like, Brushes, Font and so on
  • It will not refer to any other parent's resources, so it fail to be used in the UserControl
  • When using the Complex Object, it takes more time to load the application

Dynamic Resources

  1. <object property="{DynamicResource key}" .../>  
  2.   
  3.   
  4.     <object>  
  5.         <object.property>  
  6.             <DynamicResource ResourceKey="key" .../>  
  7.         </object.property>  
  8.     </object> 
  • It may be called as an On Demand Resource because it actually loads the object but not the value until the object is needed during the runtime
  • It will assign the value whenever the object is demanded for the same
  • It will refer to the value whenever it is required, maybe refreshed
  • It is a very optimal way to use it whenever we change the value by code behind
  • Here it will assign the resource to any other control, so it is referred to in the UserControl from its hosted parent
  • It loads quickly, even if it is a heavily used resource object


Data Conversion

Data conversion is nothing but converting the type as required and we need to implement IValueConverter to do this. For example, we can't directly bind a bool property to a Visibility property of a control because of different data types, so in this case data conversion plays a converter role to bind the data as required.



The following is an example of binding with a converter in XAML:

  1. <Window x:Class="SimpleBinding.MainWindow"  
  2.         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.         xmlns:local="clr-namespace:SimpleBinding"  
  5.         Title="MainWindow" Height="350" Width="525">  
  6.     <Window.Resources>  
  7.         <local:BoolToVisibleConverter x:Key="booltovisi"/>  
  8.     </Window.Resources>  
  9.   
  10.         <Grid>  
  11.   
  12.         <TextBox Visibility="{Binding VisiProp, Converter={StaticResource booltovisi}}"/>  
  13.   
  14.     </Grid>  
  15. </Window> 

The following is an example of an IValueConverter implementation in Code Behind:

  1. public class BoolToVisibleConverter : IValueConverter  
  2.     {  
  3.         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)  
  4.         {  
  5.   
  6.             if ((bool)value)  
  7.                 return Visibility.Visible;  
  8.             else  
  9.                 return Visibility.Hidden;  
  10.         }  
  11.   
  12.         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)  
  13.         {  
  14.             return null;  
  15.         }  
  16.     } 

Data Validation

This is the process of validating the data when progressing on it. For example if a user provides an invalid value on a required field then it will alert the user of the mistake as an indicator or a message. Like the case of a TextBox that is getting the age, that should alert the user when entering an invalid value.

These can be validated using ValidationRule that can validate the value as required.

In XAML

  1. <TextBox>  
  2.             <TextBox.Text>  
  3.                 <Binding Path="AgeOfPerson">  
  4.                     <Binding.ValidationRules>  
  5.                         <local:AgeValidation ValidationStep="RawProposedValue"/>  
  6.                     </Binding.ValidationRules>  
  7.                 </Binding>  
  8.             </TextBox.Text>           
  9.         </TextBox> 

The following is an example of ValidationRule implementation in Code Behind:

  1. public class AgeValidation : ValidationRule  
  2.     {  
  3.         public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)  
  4.         {  
  5.             int intValue;  
  6.             if (int.TryParse(value.ToString(), out intValue))  
  7.                 return new ValidationResult(truenull);  
  8.   
  9.             return new ValidationResult(false"Entera valid correct value.");  
  10.         }  
  11.     } 


Data Template

This is a model that enables you to have your own representation of the data. WPF controls have built-in functionality to support the customization of data presentation. Also the templates based on custom logic and the support for the display of hierarchical data.

For example let us assume that the data in a List Box should be a button and when clicked it will show a message box that contains a Wish message with its content.

XAML

  1. <ListBox ItemsSource="123456789">  
  2.             <ListBox.ItemTemplate>  
  3.                 <DataTemplate>  
  4.                     <Button Content="{Binding}" Height="50" Width="150" Click="Button_Click_1"/>  
  5.                 </DataTemplate>  
  6.             </ListBox.ItemTemplate>  
  7.         </ListBox> 

The following is an example of the Code Behind for the message box logic:

  1. private void Button_Click_1(object sender, RoutedEventArgs e)  
  2. {  
  3.     MessageBox.Show("Hi I am Button : " + (sender as Button).Content.ToString());  

Triggers

Triggers are a concept of changing a value depending on a condition. Here we can have the desired value depending on the condition. And the Triggers are further classified into the following three types:

  • Property Triggers
  • Data Triggers
  • Event Triggers


Property Triggers

It depends on a property, whenever the property is changed, it triggers and performs the action depending on the conditions. It is the most commonly used trigger. For example the following code will trigger depending on the property that changes the foreground color of a Button during a Mouse Over.

XAML Coding

  1. <Button Content="Valga Tamil! Valarga Tamil!!" FontSize="18" HorizontalAlignment="Center" VerticalAlignment="Center">  
  2.             <Button.Style>  
  3.                 <Style TargetType="Button">  
  4.                     <Setter Property="Foreground" Value="Orange"></Setter>  
  5.                     <Style.Triggers>  
  6.                         <Trigger Property="IsMouseOver" Value="True">  
  7.                             <Setter Property="Foreground" Value="DarkViolet" />  
  8.                         </Trigger>  
  9.                     </Style.Triggers>  
  10.                 </Style>  
  11.              </Button.Style>  
  12.         </Button> 







Data Trigger

This is triggered based on the data provided. Here there is no need to have the property as a dependency property. For example here we change the text depending on the language choosen using explicit elements.

XAML Code

  1. <CheckBox Name="Language" Content="In Tamil Language" />  
  2.             <TextBlock HorizontalAlignment="Center" Margin="0,20,0,0" FontSize="15" Foreground="Orange">  
  3.                 <TextBlock.Style>  
  4.                     <Style TargetType="TextBlock">  
  5.                         <Setter Property="Text" Value="Tamil Valga! Tamil Valarga!!" />  
  6.                         <Style.Triggers>  
  7.                             <DataTrigger Binding="{Binding ElementName=Language, Path=IsChecked}" Value="True">  
  8.                                 <Setter Property="Text" Value="தமிழ் வாழ்க! தமிழ் வளர்க!!" />  
  9.                             </DataTrigger>  
  10.                         </Style.Triggers>  
  11.                     </Style>  
  12.                 </TextBlock.Style>  
  13.             </TextBlock> 



Event Trigger

This will trigger based on events and is usually used with animation by the help of a story board. For example here a TextBlock Font size will change based on the event that fires (like Mouse Enter and Mouse Leave).

XAML Code

  1. <TextBlock Text="தமிழ் வாழ்க! தமிழ் வளர்க!!" Foreground="Orange" FontSize="10" HorizontalAlignment="Center" VerticalAlignment="Center">  
  2.                 <TextBlock.Style>  
  3.                     <Style TargetType="TextBlock">  
  4.                         <Style.Triggers>  
  5.                             <EventTrigger RoutedEvent="MouseEnter">  
  6.                                 <EventTrigger.Actions>  
  7.                                     <BeginStoryboard>  
  8.                                         <Storyboard>  
  9.                                             <DoubleAnimation Duration="0:0:1" Storyboard.TargetProperty="FontSize" To="15" />  
  10.                                         </Storyboard>  
  11.                                     </BeginStoryboard>  
  12.                                 </EventTrigger.Actions>  
  13.                             </EventTrigger>  
  14.                             <EventTrigger RoutedEvent="MouseLeave">  
  15.                                 <EventTrigger.Actions>  
  16.                                     <BeginStoryboard>  
  17.                                         <Storyboard>  
  18.                                             <DoubleAnimation Duration="0:0:1" Storyboard.TargetProperty="FontSize" To="10" />  
  19.                                         </Storyboard>  
  20.                                     </BeginStoryboard>  
  21.                                 </EventTrigger.Actions>  
  22.                             </EventTrigger>  
  23.                         </Style.Triggers>  
  24.                     </Style>  
  25.                 </TextBlock.Style>  
  26.             </TextBlock>