Data Binding is one of the most important services offered by WPF. Data Binding just means connecting the user interface to the information to be displayed. The data source can be properties data from the database, xml or other element property which includes the graphical elements as well.

Binding Targets

Data Binding has a Target and the Target has to be an element in the User Interface.  The syntax below can be used for the Data Binding.

 

WPF Binding Target

WPF Binding Target

Binding is the class that derives from the markup extension base class. And the various properties of the Binding object can be set. This binding object will be incharge of the Text property value of the object. The object that owns this Text property can be FrameworkElement. We can also bind to framework content elements. WPF also allows us to bind with certain types that are not framework elements but can be associated with them like the Brush object. So as long as Brush is a property of the Framework Element we can use it in binding. Binding is a framework service and Binding also takes into account context of the Visual Tree. The Target property has to be a dependency property. A dependency property is a property which is managed by the WPF property system and almost all properties of framework elements are dependency properties.

Binding Expressions

As far as the source of the binding is concerned any .NET object can be used as a source. We also need to specify what part of the source we are talking about. So the binding markup syntax lets us set that. So using the Path property of the Binding helps us specify which property of the source object is to be used as a binding and if want to bind to the entire object rather than a property of the object then we do not need to specify the Property. If we are binding with an XML then we need to bind to the XPath property to specify the element to bind to in the XML. Another important property in Binding is Mode which determines which way the binding will behave with the source.

 

The binding system of WPF defines the appropriate default modes for the various WPF elements. For Example it will default the mode to two way for a textbox and one way for textbock.

Bindings in Code

In xaml we use markup extension to define our bindings. In code we can set the binding directly by calling the SetBinding method of the FrameworkElement. We have passed the path as a constructor parameter.

 

WPF Binding in Code

WPF Binding in Code

Another way of setting the binding is by using the BindingOperations helper class. This is useful when we are not aware of the target type at the compile time.

Explicit Data Source for Binding

For a binding to work properly we need to define its source. In the example below we have explicitly specified the Source for the Binding in xaml. So we have specified the source as current thread and the path as CurrentCulture.

WPF Explicit Data Source Binding

WPF Explicit Data Source Binding

 

But you should know that this is not how usually the Binding is done in WPF.

Explicit Data Source as Resource

This is somehow close to the way we usually do the data binding. We have a source object placed in the Resources section and multiple objects are using this source object. The Resources object is a dictionary in which we can put useful objects. And then we have bound this source objects to multiple textblocks. One of them does not specify a path so the textblock is bound to the entire source object and the source being a string it works out fine. The second textblock specifies the path as the length property

 

WPF Explicit Data Source Resource

WPF Explicit Data Source Resource

Data Contexts

Let’s see how we usually do data binding in WPF. With the use of data context we can hook up multiple controls to share the same source for the data bindings. We have set the data context property of the Grid. If the Source property is not set in the Data Binding then the Control looks for the Data Context. But there is no Data Context for the TextBlocks but just for the Grid. Data Context is an inherited property and the way It works is it flows down to the descendants so the textblocks inherit the data context from the grid. And this DataContext becomes the implicit source of these bindings and the bindings just specify the path.

 

WPF Data Context

WPF Data Context

You would notice that I have not specified the properties (Platform, Version and ServicePack) as path. This is valid as we saw in the previous section we used a constructor to specify the path same is the case here when xaml interprets these properties as the constructor arguments.

Let’s build a WPF App with Custom Class and Data Binding. Let’s create a class named Person and it will have two properties: Name and Age. Add the following code to the Person class. This class will act as a data source for us.

 

WPF Data Context

WPF Data Context

Now let’s design the User Interface for displaying the data. Add the following code the xaml. You will see that we have set the binding on the text property of the nameText and ageText to the Name and Age properties of the person class.

 

WPF Data Context

WPF Data Context

When we run the application we will see that the textboxes have picked the name and age properties.

 

WPF Data Context

WPF Data Context

As you know by default TextBox have the Binding Mode set as TwoWay. Let’s add a button to test this.

 

WPF Data Context

WPF Data Context

When we run this we will find that that when we click on show button after making the changes we will see that the value of the property is updated. But if we use the shortcut key Alt+S, we will see that the value of the property is not updated. The reason is that by default WPF updates the target when the focus is lost from the control. When we click the Show button by mouse the focus is changed from the textbox but when we use the Alt+S keyboard shortcut the focus is not changed and hence the target is not updated. To fix this we need to set the binding property named UpdateSourceTrigger to PropertyChanged on the textbox. So whenever the property is changed the source is updated.

 

WPF Data Context

WPF Data Context

When we run the application now and use the Alt+S we will see that the property is updated straight away. Now let’s see what happens when the source is updated. Let’s add another button to the view and a handler for it.

 

WPF Data Context

WPF Data Context

When we run this and click on Age + 1 button we will see that the textbox age value is not updated but when we click on show we see that the property is updated. The reason is that the data binding is not polling the property regularly as we have not told it to do so. So let’s the WPF know to poll the property. One way to do is to call the UpdateTarget on the Age + 1 button click.

 

WPF Data Context

WPF Data Context

Now when we run the application we will see that the display is also updated along with the property but this very crude way of updating the display. So let’s remove this UpdateTarget call from our code and let’s go to Person class and implement the INotifyPropertyChanged interface. This interface consists of a single event that gets raised anytime a property is changed. Also we modify the set accessor to call the change notification.

 

WPF Data Context

WPF Data Context

Now when we run the application everything works out to be fine.

Data Templates

It is very common for an application to show same kind of data over and over or show the same data at multiple places. WPF provides Data Templates for this purpose. So if we specify the Data Template for a class then that class can use it for displaying the data. The data template could work by just specifying it in the xaml along with the binding expressions.  Let’s copy the xaml from the previous sample and add it inside the data template.

 

WPF Data Context

WPF Data Context

And let’s add the following code to the code behind.

 

WPF Data Context

WPF Data Context

This way we have used data template for the task which were doing before using data template. To see the usefulness of the Data Template we need to add the following code to the code behind.

 

WPF Data Context

WPF Data Context

Now modify the xaml to make use of this data source which is a List of Person.

 

WPF Data Context

WPF Data Context

Here we have used the Person class as our item template but we can also set our item template property inline in xaml or when we specify our data template on the resources we might give it a key and then we can refer to that by using the key in the resource markup extension.

Data Triggers

There would be a requirement at times when you want to change some property of the control based on the change in value or data. So that is when Data Triggers come into picture as they will help us distinguish the data templates. Let’s see a Data Trigger in action. As we can see in the image below we have added a data trigger in Data Template so that whenever the value of the Age property becomes 21 the background of the label will change to Red.

 

WPF Triggers

WPF Triggers

Triggers are pretty basic and they can only check constant value. We cannot do any complex checks with triggers. But we can take care of that via ValueConverters.

We can also use data triggers to trigger animation. Just add the code below to the xaml file.

 

WPF Triggers

WPF Triggers

We can also use EventTriggers or MultiTriggers in DataTemplates as well.

Binding To Collections

As we can see in the image below we have binded the ListBox to a Collection of SystemFontFamilies. You will also notice that we have not set the binding here just mentioned the static resource. The ItemsControl does not mind this until its getting a collection in return to bind to. We have set the Data Template inline. Here we have bound the TextBlock to a Non Text property which is the Font Family object itself. All ItemsControl (ListBox, ComboBox, ListView, TabControl, TreeView, Menu) support this kind of binding. We should be cautious not to add any items to its children or to its items property if we have used the ItemsControl property. An ItemsControl must be either used in the DataBound mode or the normal mode. Otherwise addig items to the ItemsSource while it already has children will result into exception.

 

WPF Collection Binding

WPF Collection Binding

Master Details of Selected Item

We might often want to showcase additional detail of the item selected. Let’s take help of an example to showcase this. Add the code shown below to the xaml. The ListBox part of the code is quite similar to the previous section except one additional property IsSynchronizedWithCurrentItem. This is because the data binding susyem will keep track of currently selected item data source and these controls are not required to sync with that so we want them to be in sync. We have also used the textboxes to display these additional details and you would see that we have bound the text property of the textboxes to a single property and this property is not present in the collection which is set to data context. So the data binding system checks if this property is present in the currently selected item and as it does it displays that value.

WPF Additional Info Binding

WPF Additional Info Binding

So we are relying on the data binding to fail in 1st attempt in order or the data binding to work. So we can fix that by adding a / to the binding and this will mean we want to bind with the currently selected item.

 

WPF Additional Info Binding

WPF Additional Info Binding

You might also notice that we have used [en-us] in the FamilyNames textblock this is because the Font Name sis a dictionary and it has different values in different culture and we are passing the locale to look entry in the dictionary. We can also dig down into sub properties by using the . syntax.

Hierarchical Binding

Sometimes we might want to bind to a data source which has child items and we would want to them to display as well so we can use Hierarchical Binding in that case. Let’s see this in action. So we have created a XmlDataProvider in Grid.Resources and then referenced it into the Hierarchical Data Template of the treeview.  And insideproperty of that we have a textblock whose text is set to xpath as title and the hierarchical data template’s itemssource property is set to xpath item. The item expression will select all the child elements called items. The same technique works for menus as well. This xml data provider can be inline or external.

 

WPF Hierarchical Binding

WPF Hierarchical Binding

The Data binding system does not make a big distinction between the xml data binding and xml data binding. We can actually mix them. Let’s see that in action. So change the XPath to Path in the TextBlock and then look at the NodeType or InnerXML or Value. So for data binding these are just objects. We can also use ordinary property style binding and xml data binding together.

Since the XMlDataProvider just uses the XML.Dome classes from Syem.XML namespace we can use the following code in the code behind to load the xml directly into the data context.

 

XML Namespaces

This is where binding with XML gets complicated. If we are not using any namespaces the xml data then the xpath would just work with the document classes. So as seen below the expression works fine with a document with no namespace but if the same expression is run with the same document but namespace then the query will return nothing.

 

We can use namespace aware syntax to do the proper data binding. We cannot specify the namespace of xml as we use to refer types in xaml. Instead we will have to use the XmlDataProvider.XmlNamespaceManager and then use the helper class XmlNamespaceMappingCollection. Then we add the Prefix as the xml namespace reference.

 

WPF XML Namespaces

WPF XML Namespaces

CollectionView

Every time we bind a ItemsControl to an XML node or an object WPF creates a collection view. This is object that manages that collection for the data binding purposes. Actually it’s the CollectionView that knows the currently selected item for that CollectionView. The CollectionView sits between the Source and the View and provides other services like data sorting, callback functions to fill the view and data grouping.

Let’s see the grouping service of the collection view at work. Add the following code your xaml file. We have to tell the collection view about our grouping requirements. Now you should remember that the collection view is always created at runtime so we cannot access it in xaml directly. So instead we have to use a collectionViewSource. This is the description in xaml that tells WPF to how to configure the CollectionView. So we have binded the collection view to the data source and grouped it from the GroupName attribute. We can have more than one CollectionViewSource for any collection. Also the controls will have to specify this CollectionView as their View Source to override the default view to that specified by the CollectionView.So we have set the ItemsSource of the MenuItem to our collection ViewSource. By default all ItemsControl have the abailty to put headers in groups and we can do this by specifying a group style which uses a data template. So we have use dthe grouping information coming from the CollectionView Source.

 

WPF Collection View

WPF Collection View

INotifyCollectionChanged

This is the interface similar to INotifypropertyChanged this interface reflects the collection level changes and its already implemented in the ObservableCollection. So this will works with Lists so when the items change on the complete list this will send the notification.  If we use a list and add items to it then the same will not reflect on the user interface even we have data binding but if we use an ObsevableCollection in the place of List we will see the changes.

Converters

Sometimes the data might not be directly suitable for the data binding. So we might want to need to convert it before it reaches the data binding. So this where the converters come into picture. All Converters in WPF bindings implement the IValueConverter. This interface has a Convert and ConvertBack method. The convertback method gets used in twoway bindings. Converters are very simple. They just get to adjust or replace data that flows between the source and the target.

Let’s see this in action. WE will be using the person class we created earlier. Add the following code to the xaml for the window.

 

WPF Converters

WPF Converters

WPF Converters

WPF Converters

 

And the following code to the code behind file.

 

WPF Converters

WPF Converters

Now create another class in the application named AgeCheckConverter.cs and add the following code to it.

 

WPF Converters

WPF Converters

You will see that we have used this converter in our DataTrigger and checked for value true. The converter does the actual logic and we get the red background if the age is less than 21. Also coverters helps us put the logic for the decision making.

Validation

The data binding system also has support for validation. We can add a set of validation rules for our binding. But to do that we need to use the syntax of binding in full. Validation rules are pretty simple. All they do is look at a value and say whether its valid or not. As we see in the example below the validations will derive from the ValidationRule base class and override the Validate method. You can see the validation rule has no context. It just gets the value. But the problem is that this validation system does not work with the multi field validations. Its more useful at places where we verify whether the strings has the required format or not.

Let’s see this in action. Add a class named MySource.cs and implement the IDataErrorInfo to do the validations.

 

WPF Validation

WPF Validation

Add the following code for the view

 

WPF Validation

WPF Validation

And add the following code behind

 

WPF Validation

WPF Validation

We will see that the textbox border becomes red when a validation error occurs.

 

Other Binding Types

We can also use Multi bindings which lets us combine multiple source values into one result so we can provide it with the connections to ordinary bindings one for each source value and then we need to provide a Multivalue converter that implements IMultiValueConverter.

Another binding is Priority binding which is used by WPF one after another until it finds a binding that works.

 

The Code for the post can be found here.

 

Any Questions, comments and feedback is most welcome.

 

 

Microsoft has been offering data binding for all its user interface applications but it was an assumption that all the data binding that will happen will always be related to database. However WPF and Silverlight have a broader view assuming that the client side code is often not connected directly to the database. And Silverlight goes a step further by not providing the ADO.NET classes to connect to the database directly. This makes sense because Silverlight is used to design web pages and most organizations do not want to put their database onto the internet for obvious security reasons. So the way data comes into a Silverlight application is in the form of objects or xml. So the data biding framework in Silverlight focuses on objects. So the purpose of data binding is to connect the features of UI to the properties of the objects. Databinding can be used with nearly any property of any element.

Binding Expressions

To bind the property of a user interface element we use the binding markup extension. As you can see in below markup extensions are specified in the curly braces which are evaluated at runtime.

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname}”/>

 

So this markup binding extension binds the path property of the TextBox to property named Surname and the value of this TextBox text property is evaluated at runtime. Data binding will always connects 2 properties: the target property (generally the user interface property) and the source property (a dependency

Data Context

Now as we saw in the last section that we need to provide the data binding along with the source and target property. So if want to bind multiple targets then we do not need to write the source individually for each of the target property as multiple targets can use the same source for data binding. Let’s have a look at this with an example.

Let’s create a Person class in you user interface with the following Fields as shown below.

namespace DataBindingInSL

{

public class Person

{

public string GivenName { get; set; }

public string Surname { get; set; }

public double Age { get; set; }

}

}

 

Now we want to bind these properties in the User Interface. So lets add the following code in the code behind file of the view.

namespace DataBindingInSL

{

public partial class MainPage : UserControl

{

Person src = new Person { GivenName = “Max”, Surname = “Smith”, Age = 34 };

 

public MainPage()

{

InitializeComponent();

 

this.DataContext = src;

}

}

}

 

Now we are setting the DataContext of the User Interface as src.  By setting the DataContext property at the root element we have made the properties available at the all the elements in the tree as the DataContext in Silverlight cascades down the tree.  We could also set the datacontext on any panel as well and in that case the datacontext will apply only to the panel and its children. Once we have set this DataContext, it becomes the implicit source for all the user Interface elements. So in the View all we need to do is the property name in the binding path and the element will pick up the property from the source i.e. Data Context. Add the following code to the xaml of you SL app.

<Grid x:Name=”LayoutRoot” Background=”White”>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″ Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName}” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″ Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname}”/>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″ Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age}”/>

</Grid>

 

When you run the application you would see that all the TextBox will display the values that are picked up from the bindings.

Data Context Silverlight 4

Data Context Silverlight 4

Right now the data is flowing in only one direction i.e. from src to the User Interface. If we want the data to flow in both the directions then we need to specify the mode as TwoWay in the Binding as shown below:

Text=”{Binding Path=Age, Mode=TwoWay}”

 

Binding Updates

As we saw in the last section that the User interface is updated with the values that are set in source at load time but when the values are updated at a later point in time then also the data binding model of Silverlight can reflect the in the source to the user interface when the data source raises change notification. The change notification can be raised after implementing the INotifyPropertyChanged.

So let’s implement the INotifyPropertyChanged interface in the data source so that whenever the source changes the User Interface is updated along with it as well. This interface has only one event which is raised whenever a property changes in the class. So change the code of the Person class as below along with the implementation of INotifyPropertyChanged.

public class Person : INotifyPropertyChanged

{

public string GivenName { get; set; }

public string Surname { get; set; }

private double _age;

 

public double Age

{

get { return _age; }

set

{

if (value != _age)

{

_age = value;

OnPropertyChanged(“Age”);

}

}

}

 

public event PropertyChangedEventHandler PropertyChanged;

 

private void OnPropertyChanged(string propertyName)

{

if (PropertyChanged != null)

{

PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

}

}

}

 

Here after the implementation of INotifyPropetyChanged we change the code inside the set method of the Age property to call the OnPropertyChanged method which in turn raises the property changed event. So now when the Age property is changed the change will reflect in the User Interface as well. Change the code of the cs and xaml file to as shown below and you will be able to see the update in the property.

 

Silverlight 4 Binding Updates

Silverlight 4 Binding Updates

Data Template

We have seen the example of an adhoc binding in the previous section but Silverlight has a more structured way of defining the same using Data Template. A Data Template is similar to a Control Template. Just as the control Template determines how the Control should like, in a similar way a Data Template determines how the particular data would look like. Data Templates can be used by ItemsControls (ListBox, etc) and ContentControl (Buttons, etc). A Data Template will work at any place where a Content Model is in place.

Whenever there are custom properties in a class then it’s a good idea to define a Data Template in xaml so that the control knows how to display those types.  Let’s see this working in code.

<UserControl.Resources>

<DataTemplate x:Key=”dataTemplateBinding” >

<Grid>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″

Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″

Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″

Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName, Mode=TwoWay}” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname, Mode=TwoWay}”/>

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”0,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age, Mode=TwoWay}”/>

</Grid>

</DataTemplate>

</UserControl.Resources>

<Grid x:Name=”LayoutRoot” Background=”White”>

<ContentControl Content=”{Binding}”

ContentTemplate=”{StaticResource dataTemplateBinding}” />

<Button Content=”Older” Height=”23″ HorizontalAlignment=”Left” Margin=”43,242,0,0″

Name=”button1″ VerticalAlignment=”Top” Width=”75″ Click=”button1_Click” />

</Grid>

</UserControl>

Binding to Collections

Instead of binding to one instance we can bind a control to a collection. Let’s modify the MainPage as below to create a collection of Person.

public partial class MainPage : UserControl

{

Person src = new Person { GivenName = “Max”, Surname = “Smith”, Age = 34 };

List<Person> people = new List<Person>();

 

public MainPage()

{

InitializeComponent();

 

people.Add(src);

people.Add(new Person { GivenName = “Steve”, Surname=”Gaylon”, Age=44};

people.Add(new Person { GivenName = “John”, Surname=”Miller”, Age=14};

 

this.DataContext = people;

}

 

private void button1_Click(object sender, RoutedEventArgs e)

{

src.Age += 1;

}

}

 

Let’s change the xaml as below:

<UserControl.Resources>

<DataTemplate x:Key=”dataTemplateBinding” >

<Grid>

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,38,0,0″

Name=”label1″ VerticalAlignment=”Top” Width=”120″ Content=”Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,95,0,0″

Name=”label2″ VerticalAlignment=”Top” Width=”120″ Content=”Last Name” />

<sdk:Label Height=”23″ HorizontalAlignment=”Left” Margin=”12,153,0,0″

Name=”label3″ VerticalAlignment=”Top” Width=”120″ Content=”Age” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,38,22,0″

Name=”textBox1″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=GivenName, Mode=TwoWay}” />

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,95,22,0″

Name=”textBox2″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Surname, Mode=TwoWay}”/>

<TextBox Height=”23″ HorizontalAlignment=”Right” Margin=”40,153,22,0″

Name=”textBox3″ VerticalAlignment=”Top” Width=”240″

Text=”{Binding Path=Age, Mode=TwoWay}”/>

</Grid>

</DataTemplate>

</UserControl.Resources>

<Grid x:Name=”LayoutRoot” Background=”White”>

<ListBox ItemsSource=”{Binding}”

ItemTemplate=”{StaticResource dataTemplateBinding}” />

<Button Content=”Older” Height=”23″ HorizontalAlignment=”Left” Margin=”43,242,0,0″

Name=”button1″ VerticalAlignment=”Top” Width=”75″ Click=”button1_Click” />

</Grid>

 

Collection Updates

The INotifyPropertyChange will work only when a property is changed but when a collection is changed we need to implement the INotifyColectionChanged. We can either use ObservalbeCollection<T> or implement this interface to get the update whenever a new item is added to the collection.

Let’s add a new button along with a new event handler to add a new item to the collection so we need to change the xaml and cs file to as below:

private void button2_Click(object sender, RoutedEventArgs e)

{

people.Add(new Person { GivenName = “Scott”, Surname = “D”, Age = 62 });

}

 

<Button Content=”Add Item” Height=”23″ HorizontalAlignment=”Left” Margin=”325,182,0,0″

Name=”button2″ VerticalAlignment=”Top” Width=”75″ Click=”button2_Click” />

 

Now replace the List<Person> with ObservableCollection<Person>.

ObservableCollection<Person> people = new ObservableCollection<Person>();

 

And that is it. Now whenever you click the Add Item button a new item will be added to the collection and also the ListBox will be updated.

 

Grouping

If we want to group the data based on some criteria then we can use the CollectionViewSource. This groups the items based on the property specified of the items.

<UserControl.Resources>
    <CollectionViewSource x:Key="mySource" Source="{Binding Path=RawItems}">
        <CollectionViewSource.GroupDiscussions>
            <PropertyGroupDiscription PropertyName="EventTrack" />
        </CollectionViewSource.GroupDiscussions>
    </CollectionViewSource>
</UserControl.Resources>

 

DataGrid internally understands grouping but the ItemsControl does not. So this is an advantage as by using the ItemsControl we can have our own custom visualizations.

 

Silverlight 4 Grouping

Silverlight 4 Grouping

When we wrap a collection in a collection view source, it provides a property known as groups.  Normally we can bind to a wrapper but we can bind to the groups property instead.

<ItemsControl ItemsSource="{Binding Path=Groups, Source={StaticResource groupSource}}">
    <ItemsControl.ItemTemplate>
            <DataTemplate>
                <ItemsControl ItemsSource="{Binding Path=Items}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
</ItemsControl>

Silverlight 4 Grouping

Hierarchical Binding

The basic ability to bind with hierarchical controls is provided by the HeadedItemsControl class. HeadedItemsControl derive from ItemsControl so the binding works in nearly the same way. The difference is in the ItemTemplate property as need to refer to HieraricalDataTemplate instead of a normal DataTemplate. The Hierarchical Data Template has one feature. It too has a ItemsSource Property.

<sdk:HierarchicalDataTemplate ItemsSource="{Binding Path=Children}">
    <TextBlock Text="{Binding Path=Label}" />
</sdk:HierarchicalDataTemplate>

Silverlight 4 Hierarchical Binding

 

Find the source code ralated to this post here.

 

Any questions, comments and feedback are most welcome.