DataBinding Expressions In WPF

There are a lot of articles which discuss the concept of Binding and explain how to bind the properties, using StaticResources and DynamicResources. These concepts use the DataBinding expressions provided by WPF. In this article, let’s explore the different types of Data Binding Expressions provided by WPF.

Introduction

Data Binding is a powerful technique, which allows the flow of data between UI Elements and Business model. It reflects the changes automatically to UI element, as soon as the data in Business model changes.

Modes of Data Binding

ModesDescription
OneWaySource → Destination
TwoWaySource ←→ Destination
OneWayToSourceSource ← Destination
OneTimeSource → Destination (only once)

This can be achieved by different types of Data Binding Expression provided by WPF.

Types of Data Binding Expressions are given below.

  • DataContext Binding
  • RelativeSource Binding
  • Current Item of Collection Binding

DataContext Binding

DataContext is a Dependency property, which is a default source of binding. Datacontext is inherited along the logical tree. Hence, if you set a datacontext to control all the child elements in the logical tree it will also refer to the same datacontext, unless and until another source is specified explicitly.

Let’s take an example to understand it in more detail.

  1. Create a class Book, as shown below.
    1. public class Book 
    2. {  
    3.     public string Name 
    4.     {  
    5.         get;  
    6.         set;  
    7.     }  
    8.     public string Author 
    9.     {  
    10.         get;  
    11.         set;  
    12.     }  
    13. }  
  2. Add a XAML file DataContextBinding.xaml and place four Textblocks, as shown below.
    1. <Grid VerticalAlignment="Center">  
    2.     <Grid.RowDefinitions>  
    3.         <RowDefinition Height="40" />  
    4.         <RowDefinition Height="40" />  
    5.     </Grid.RowDefinitions>  
    6.     <Grid.ColumnDefinitions>  
    7.         <ColumnDefinition Width="Auto" />  
    8.         <ColumnDefinition Width="Auto" />  
    9.     </Grid.ColumnDefinitions>  
    10.     <TextBlock Text="Book Name:" FontWeight="Bold" />  
    11.     <TextBlock Grid.Column="1" />  
    12.     <TextBlock Text="Author:" FontWeight="Bold" Grid.Row="1" />  
    13.     <TextBlock Grid.Row="1" Grid.Column="1" />  
    14. </Grid>  
         Now, let’s see how this DataContext property is used to display the data.

         It is used in two ways, which are given below.

  1. Using {Binding} expression

    Used to bind the DataContext directly.

    Create an instance of class Book, initialize its properties and assign the Name property of the class to the DataContext property of Window.

    1. public partial class DataContextBinding: Window 
    2. {  
    3.     public DataContextBinding() 
    4.     {  
    5.         InitializeComponent();  
    6.         //Create the instance  
    7.         Book book = new Book();  
    8.         //initialize the properties  
    9.         book.Name = "Computer Networking";  
    10.         //Assign the Property as DataContext  
    11.         this.DataContext = book.Name;  
    12.     }  
    13. }  

    As the Datacontext is inherited along the logical tree and the data book, name is bound to Control Window. All the child elements of Window will also refer to same object (book.Name).

    To display the data, bind the DataContext with the Textblock, as shown below.

    1. <TextBlock Text="Book Name:" FontWeight="Bold"/>  
    2. <TextBlock Text="{Binding}" Grid.Column="1" />   

    OUTPUT



  2. Using {Binding Property} expression

    Binds the property of Datacontext.

    Create an instance of class Book, initialize its properties and assign instance of class (book) to the DataContext property of Window. 

    1. Book book = new Book();  
    2. //initialize the properties  
    3. book.Name = "Computer Networking";  
    4. book.Author = "James F. Kurose";  
    5. //Assign the instance as DataContext  
    6. this.DataContext = book;  

    Now, let’s see the output.

        

    As the Binding expression {Binding} is used to bind the DataContext object of type Book, ToString() method is called on it and the data is shown as a string.To display the data in proper format, we have to bind the properties of data object with the Textblocks, as shown below:

  1. <TextBlock Text="Book Name:" FontWeight="Bold"/>  
  2. <TextBlock Text="{Binding Name}" Grid.Column="1" />  
  3. <TextBlock Text="Author:" FontWeight="Bold" Grid.Row="1" />  
  4. <TextBlock Text="{Binding Author}" Grid.Row="1" Grid.Column="1"/>   

Binding expression {Binding Name} is used to bind the Name property of DataContext bound.

OUTPUT
                                                                                                                                                           

RelativeSource Binding

RelativeSource is a property, which sets the binding source with the relative relation to bind the target. This extension is majorly used when you have to bind one property of the element to another property of the same element.

There are four types of RelativeSource, which are given below.

  1. Self
  2. FindAncestor
  3. TemplatedParent
  4. PreviousData

Let’s explore them one-by-one in detail.

Self

Self is used in a scenario, when the Binding source and the binding target are same. One property of the object is bound with another property of the same object.

For example- let’s take an Ellipse with same height and width.

Add the code given below in XAML file. Width property is bound with height property relatively.

  1. <Grid>  
  2.     <Ellipse Fill="Black" Height="100" Width="{Binding RelativeSource={RelativeSource Self},Path=Height}">  
  3.     </Ellipse>  
  4. </Grid>   

OUTPUT

 

If the height of Ellipse is changed, the width will also change relatively.

FindAncestor

As the name says, this is used when the binding source is one of the Ancestors (Parents) of the binding targets. Using FindAncestor extension, you can find ancestor up to any level.

Let’s take an example to understand it more clearly.

Steps

Create XAML, which represents the logical tree of elements given below.

 

  1. <Grid Name="Parent_3">  
  2.     <StackPanel Name="Parent_2">  
  3.         <Border Name="Parent_1">  
  4.             <StackPanel x:Name="Parent_0" Orientation="Vertical">  
  5.                 <Button></Button>  
  6.             </StackPanel>  
  7.         </Border>  
  8.     </StackPanel>  
  9. </Grid>  

Now, let’s use FindAncestor extension to bind the Name Property of the ancestors to the Content Property of Child element button.

  1. <Grid Name="Parent_3">  
  2.     <StackPanel Name="Parent_2" HorizontalAlignment="Center" VerticalAlignment="Center" Width="100">  
  3.         <Border Name="Parent_1">  
  4.             <StackPanel x:Name="Parent_0" Orientation="Vertical">  
  5.                 <Button Height="50" Content="{Binding RelativeSource={RelativeSource FindAncestor,  
  6. AncestorType={x:Type StackPanel},  
  7. AncestorLevel=2},Path=Name}"></Button>  
  8.             </StackPanel>  
  9.         </Border>  
  10.     </StackPanel>  
  11. </Grid>  

OUPUT

 

AncestorType “StackPanel” in combination with AcestorLevel as “2” binds the content property of button with the Name property of StackPanel (Parent_2).

TemplatedParent

TemplatedParent is a property, which enables you to create a Control template with few unknown values. These values depend on the properties of control that ControlTemplate is applied to. 

Let’s take an example to understand it in more detail

Steps

  1. Create a ControlTemplate for button, as shown below. 
    1. <Window.Resources>  
    2.     <ControlTemplate x:Key="template">  
    3.         <Canvas>  
    4.             <Ellipse Height="110" Width="155"  
    5.              Fill="Black"/>  
    6.             <Ellipse Height="100" Width="150"  
    7.              Fill="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Background}">  
    8.             </Ellipse>  
    9.             <ContentPresenter Margin="35"  
    10.              Content="{Binding RelativeSource={RelativeSource TemplatedParent},Path=Content}"/>  
    11.        </Canvas>  
    12.     </ControlTemplate>  
    13. </Window.Resources>  

    In the code given above, sample Fill Property of Ellipse and Content Property of ContentPresenter is dependent on the values of properties of control to which this template will be applied.

  1. Add a button and apply the template to it.
    1. <Button Margin="50" Background="Beige" Template="{StaticResource template}" Height="0" Content="Click me" FontSize="22">  
    2. </Button>   

    As the template is applied, the Background (Beige) of button is relatively bound with Fill Property of Ellipse and Content (Click me) is relatively bound with Content property of ContentPresenter. The dependent values are evaluated and gives the output given below.

    OUTPUT

         

PreviousData

This is the least used mode of RelativeSource. This comes into the picture when data is analyzed and we need to represent the change in values with respect to previous data.

Let’s take an example to understand it in more detail.

Steps

  1. Create a class Data and implement INotifyPropertyChanged interface, as shown below 
    1. public class Data: INotifyPropertyChanged 
    2. {  
    3.     public int DataValue 
    4.     {  
    5.         get;  
    6.         set;  
    7.     }  
    8.     public event PropertyChangedEventHandler PropertyChanged;  
    9.     protected void OnPropertyChanged(string PropertyName) 
    10.     {  
    11.         if (null != PropertyChanged) 
    12.         {  
    13.             PropertyChanged(this,  
    14.                 new PropertyChangedEventArgs(PropertyName));  
    15.         }  
    16.     }  
    17. }   
  1. Create a list to type Data and assign it as the DataContext. 
    1. public RelativeSourcePreviousData() 
    2. {  
    3.     InitializeComponent();  
    4.     List < Data > data = new List < Data > ();  
    5.     data.Add(new Data() 
    6.     {  
    7.         DataValue = 60  
    8.     });  
    9.     data.Add(new Data() 
    10.     {  
    11.         DataValue = 100  
    12.     });  
    13.     data.Add(new Data() 
    14.     {  
    15.         DataValue = 120  
    16.     });  
    17.     this.DataContext = data;  
    18. }   
  1. Add ItemsControl in XAML file.
    1. <ItemsControl ItemsSource="{Binding}"></ItemsControl>  
  1. Create ItemsPanel Template for it, as shown below. 
    1. <ItemsControl ItemsSource="{Binding}">  
    2.     <ItemsControl.ItemsPanel>  
    3.         <ItemsPanelTemplate>  
    4.             <StackPanel Orientation="Vertical" />  
    5.         </ItemsPanelTemplate>  
    6.     </ItemsControl.ItemsPanel>  
    7. </ItemsControl>  
  1. Now, for proper representation of data, create DataTemplate, as shown below.
    1. <ItemsControl.ItemTemplate>  
    2.     <DataTemplate>  
    3.         <StackPanel Orientation="Horizontal">  
    4.             <Grid Margin="30,20,0,0">  
    5.                 <Rectangle Width="80" Height="{Binding DataValue}" Fill="Blue" />  
    6.                 <TextBlock Foreground="White" Margin="35,0,0,0" Text="{Binding DataValue}"></TextBlock>  
    7.             </Grid>  
    8.             <TextBlock Margin="30,20,0,0" Text="Previous Data:"></TextBlock>  
    9.             <TextBlock VerticalAlignment="Center" Margin="5,20,0,0" Text="{Binding  
    10.              RelativeSource={RelativeSource PreviousData}, Path=DataValue}" />  
    11.         </StackPanel>  
    12.     </DataTemplate>  
    13. </ItemsControl.ItemTemplate>  

    OUTPUT

        

The Height of Blue boxes is the value of the items in list and the previous data is shown at right with respect to boxes. The first value of the item is “60”. Therefore, the previous data shows no value for first item.

Current Item of Collection Binding

This is used when you are working with Collection. You can read the properties of SelectedItem very easily, using this binding expression. The slash is a special operator, which is used to deal with current item in the collection.

There are three kind of expressions, which are used given below.

  1. {Binding / }
  2. {Binding Collection / }
  3. {Binding Collection / Property}

{Binding / }

This expression is used to bind the current item in the DataContext.

Let’s take an example:-

In the example given below, DataContext is a collection of countries of string type and same is bound with the Listbox.

Steps

  1. Create a class Countries and add a method GetCountriesName(), which returns the collection of countries of string data type, as shown below. 
    1. public class Countries 
    2. {  
    3.     public static List < string > GetCountriesName() 
    4.     {  
    5.         List < string > countries = new List < string > ();  
    6.         foreach(CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) 
    7.         {  
    8.             RegionInfo country = new RegionInfo(culture.LCID);  
    9.             if (!countries.Contains(country.EnglishName))  
    10.                 countries.Add(country.EnglishName);  
    11.         }  
    12.         countries.Sort();  
    13.         return countries;  
    14.     }  
    15. }  
  1. Add a XAML file, add Listbox and TextBlock, as shown below.
    1. <DockPanel Name="Collection">  
    2.     <ListBox ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True">  
    3.     </ListBox>  
    4.     <TextBlock DockPanel.Dock="Top" />  
    5. </DockPanel>  
  1. Create the instance of class Countries and assign the collection of countries as DataContext.
    1. public CurrentItemCollection() 
    2. {  
    3.     InitializeComponent();  
    4.     Countries countries = new Countries();  
    5.     this.DataContext = countries.GetCountriesName()  
    6. }  
  1. Bind the Text property of TextBlock to bind it with the current selected item of the collection, as shown below.
    1. <TextBlock DockPanel.Dock="Top" Text="{Binding /}" />  

    OUTPUT

        

         As soon as the item is selected Item, it displays the selected country on the right.

{Binding Collection / }

This expression is used to bind the current item of the Collection property within the DataContext.

For Example,

DataContext is Countries class

Collection property is CounriesList, which is bound with the ListBox.

Steps

  1. Use the same class Countries created above with a slight difference. Create a method with return type RegionInfo.
    1. public static List <RegionInfo> GetCountries() 
    2. {  
    3.     List <RegionInfo> countries = new List <RegionInfo> ();  
    4.     foreach(CultureInfo culture in CultureInfo.GetCultures(CultureTypes.SpecificCultures)) 
    5.     {  
    6.         RegionInfo country = new RegionInfo(culture.LCID);  
    7.         if (countries.Where(p => p.Name == country.Name).Count() == 0)  
    8.             countries.Add(country);  
    9.     }  
    10.     return countries.OrderBy(p => p.EnglishName).ToList();  
    11. }
  1. Add a CountriesList property of type RegionInfo.
    1. private List <RegionInfo> countries = null;  
    2. public List <RegionInfo> CountriesList 
    3. {  
    4.     get 
    5.     {  
    6.         if (countries == null)  
    7.             countries = GetCountries();  
    8.         return countries;  
    9.     }  
    10. }  

    Below is the screenshot of values in CountriesList collection.

        
  1. Specify the class Countries as the DataContext and bind the Listbox with the CountriesList property of DataContext.
    1. <Window.Resources>  
    2.     <vm:Countries x:Key="Countries"></vm:Countries>  
    3. </Window.Resources>  
    4. <Grid>  
    5.     <DockPanel Name="Collection" DataContext="{StaticResource Countries}">  
    6.         <ListBox ItemsSource="{Binding CountriesList}" IsSynchronizedWithCurrentItem="True">  
    7.             <ListBox.ItemTemplate>  
    8.                 <DataTemplate>  
    9.                     <TextBlock Text="{Binding EnglishName}"></TextBlock>  
    10.                 </DataTemplate>  
    11.             </ListBox.ItemTemplate>  
    12.         </ListBox>  
    13.     </DockPanel>  
    14. </Grid>  
  1. To evaluate the current item of CountriesList property, bind the Text property of TextBlock, as shown below.
    1. <TextBlock DockPanel.Dock="Top" Text="{Binding CountriesList/}" HorizontalAlignment="Center" FontSize="16" VerticalAlignment="Center" />  

    OUTPUT

        

         Right side displays the current item of the Collection (CountriesList) within the DataContext (Countries).

{Binding Collection / Property}

This expression is used to bind the property of the current item of Collection within the DataContext.

For example, if we have to evaluate a specific property of the current item of CountriesList collection.

In this example, I want to show the value of property "EnglishName".

 

To do so, bind the Text Property of TextBlock, as shown below.

  1. <TextBlock DockPanel.Dock="Top" Text="{Binding CountriesList/EnglishName}" />  
OUTPUT
 
 

Now, it shows the value of property “EnglishName”, as the item in the list is selected.

Conclusion

I have covered all the data binding expressions in detail. I hope this helps you to understand the concept of Binding and Expressions provided by WPF.