Silverlight 4.0 CollectionViewSource with WCF RIA Services

This article introduces the “CollectionViewSource” element available in Silverlight (using WCF RIA Services) and also discusses applying filters to existing data using “CollectionViewSource.”

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 4
July 19, 2010
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

To make this article simple, I managed to create a simple Silverlight 4.0 application which consumes a WCF RIA Service created using the WCF RIA Service Library.  If you are not familiar with developing applications using the WCF RIA Service Library and Silverlight 4.0, check out a beginner’s article available at http://jagchat.spaces.live.com/blog/cns!41050F68F010A662!4439.entry.

The solution was developed using Microsoft Visual Studio 2010 Ultimate Edition with Microsoft Silverlight 4.0 on Windows 7 Ultimate edition. I didn’t really test it in any other environment. I request that you post in the discussion area if you have any problems with execution.

Working with CollectionViewSource in Siverlight

Using a WCF RIA Service, we can somehow bring data down to a Silverlight application. Once the data is available to the Silverlight application, we may want to have it be viewed in different logical ways (such as a sorted view, filtered view etc.). “CollectionViewSource” is mainly designed to have view-like scenarios against the data already available in Silverlight. Not only that, but we can also track and work with the “current” item. We will discuss these soon.

Let us start with an example.

<UserControl x:Class="SLBusinessAppWithRiaLib.CvsBasic"

 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

 mc:Ignorable="d"

 d:DesignHeight="300" d:DesignWidth="400"

 xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" Width="500" Height="500">

 <UserControl.Resources>

 <CollectionViewSource x:Key="cvsEmp"/>

 </UserControl.Resources>

 

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

 <Grid.RowDefinitions>

 <RowDefinition Height="*" />

 </Grid.RowDefinitions>

 

 <sdk:DataGrid 

 x:Name="dgEmp"

 Margin="8" MinHeight="200" IsReadOnly="True" />

 

 </Grid>

</UserControl>

The above code contains the declarations for a “DataGrid” and “CollectionViewSource.” You should also note that “CollectionViewSource” is defined in the “Resources” of the Silverlight user control (or page). At this point, we have not brought any data to Silverlight yet. Also, “DataGrid” and “CollectionViewSource” in the above code are not related to each other (we bind them in code).

Let us modify the code behind as follows:

Imports System.ServiceModel.DomainServices.Client

Imports System.Windows.Data

 

Partial Public Class CvsBasic

Inherits UserControl

 

Private oCtxt As New BusinessLib.Web.EmpMgrDomainSvc

Private oCvsEmp As CollectionViewSource

 

Public Sub New()

InitializeComponent()

 

oCvsEmp = CType(Me.Resources("cvsEmp"), CollectionViewSource)

oCvsEmp.Source = oCtxt.emps

oCtxt.Load(oCtxt.GetEmpsQuery())

Me.dgEmp.ItemsSource = oCvsEmp.View

 

End Sub

 

End Class

The next section explains the above code.

CollectionViewSource in Siverlight: code explained

This section explains the code provided in the previous section.

We start by defining a domain object as follows:

Private oCtxt As New BusinessLib.Web.EmpMgrDomainSvc

To refer the “CollectionViewSource” element in markup, I declared a reference variable as follows:

Private oCvsEmp As CollectionViewSource

I get hold of the “CollectionviewSource” element available in the “Resources” section (of the markup) using the following statement:

oCvsEmp = CType(Me.Resources("cvsEmp"), CollectionViewSource)

Once the “CollectionViewSource” object is ready, I need to provide data (source) for it. Once the data is available to “CollectionViewSource,” I can view it in any logical manner. I can assign an entity set as a source for “CollectionViewSource” as shown below:

oCvsEmp.Source = oCtxt.emps

The entity set is not populated yet. We need to populate the entity set with a query, and the following statement is used for that:

oCtxt.Load(oCtxt.GetEmpsQuery())

As the entity set is already assigned to “CollectionViewSource,” the moment we populate the entity set, the data will be available to “CollectionViewSource” as well.

Once the data is available to “CollectionViewSource,” you can pull the data in to the “DataGrid” with the following statement:

Me.dgEmp.ItemsSource = oCvsEmp.View

The following is the output:

How to filter data in CollectionViewSource using Siverlight

In the previous section, we saw how to use “CollectionViewSource” in a Silverlight application. We have not really used the features of “CollectionViewSource” yet.

In this section, we are going to concentrate on filtering data using “CollectionViewSource.” Let us modify the markup as follows:

<UserControl x:Class="SLBusinessAppWithRiaLib.CvsWithFilter"

 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"

 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"

 mc:Ignorable="d"

 d:DesignHeight="300" d:DesignWidth="400"

 xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" Width="500" Height="500">

 <UserControl.Resources>

 <CollectionViewSource x:Key="cvsEmp"/>

 </UserControl.Resources>

 

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

 <Grid.RowDefinitions>

 <RowDefinition Height="Auto"></RowDefinition>

 <RowDefinition Height="*" />

 </Grid.RowDefinitions>

 <StackPanel Orientation="Horizontal" Margin="8" >

 <sdk:Label Content="Enter Dept Number:" />

 <TextBox x:Name="txtDeptFilter" MinWidth="50" Margin="5, 0, 0, 0" />

 <Button x:Name="btnApplyFilter" Content="Apply Filter" Margin="5, 0, 0, 0" />

 </StackPanel>

 <sdk:DataGrid 

 x:Name="dgEmp"

 Margin="8" Grid.Row="1" MinHeight="200" IsReadOnly="True" />

 

 </Grid>

</UserControl>

The above markup would lay out the Silverlight controls as shown below:

The following is the modified code which applies a filter to “CollectionViewSource.”

Private Sub btnApplyFilter_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnApplyFilter.Click

If String.Compare(btnApplyFilter.Content.ToString(), "Apply Filter", StringComparison.OrdinalIgnoreCase) = 0 Then

oCvsEmp.View.Filter = New Predicate(Of Object)(AddressOf DeptFilter)

oCvsEmp.View.Refresh()

btnApplyFilter.Content = "Clear Filter"

Else

oCvsEmp.View.Filter = Nothing

oCvsEmp.View.Refresh()

btnApplyFilter.Content = "Apply Filter"

End If

End Sub

 

Private Function DeptFilter(ByVal o As Object) As Boolean

If String.IsNullOrEmpty(Me.txtDeptFilter.Text) Then

Return False

End If

Dim oEmp As BusinessLib.Web.emp = o

Return oEmp.deptno = Me.txtDeptFilter.Text

End Function

 

Private Sub txtDeptFilter_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles txtDeptFilter.TextChanged

If String.Compare(btnApplyFilter.Content.ToString(), "Clear Filter", StringComparison.OrdinalIgnoreCase) = 0 Then

oCvsEmp.View.Refresh()

End If

End Sub

The next section explains the above code.

How to filter data in CollectionViewSource using Siverlight: code explained

This section explains the code provided in the previous section. For an understanding of the objects used in code, please refer to the first two sections.

Every “CollectionViewSource” maintains a “View” object within itself. However, a “CollectionViewSource” itself is not a “View.” And, to show data in different logical ways, we actually deal with “View” inside the “CollectionViewSource.”

To filter data in “CollectionViewSource,” we work with the “Filter” property available as part of “View” object. The following is the code which filters a “CollectionViewSource.”

oCvsEmp.View.Filter = New Predicate(Of Object)(AddressOf DeptFilter)

oCvsEmp.View.Refresh()

We are not filtering data directly. The “filter” is the “Deptfilter” function, which is defined as follows:

Private Function DeptFilter(ByVal o As Object) As Boolean

If String.IsNullOrEmpty(Me.txtDeptFilter.Text) Then

Return False

End If

Dim oEmp As BusinessLib.Web.emp = o

Return oEmp.deptno = Me.txtDeptFilter.Text

End Function

The “DeptFilter” function gets executed for each object available in the entity set. The object will be available through a parameter (in this case it is “o”) for the function. If the function returns true, the object will be available through “View.” If the function returns false, the object will not be shown through “View.” In the above code snippet, “DeptFilter” returns true if and only if the “oEmp.deptno” matches the content available in textbox.

Following is the output:

You can also understand from the above figure that the button turns to “Clear Filter” once you click on “Apply filter,” thanks to the following line:

btnApplyFilter.Content = "Clear Filter"

Now that we have learned how to apply filters to “CollectionViewSource,” we also need to learn how to remove an applied filter. The following is the code:

oCvsEmp.View.Filter = Nothing

oCvsEmp.View.Refresh()

btnApplyFilter.Content = "Apply Filter"

Once you click on “Clear Filter,” it should clear your applied filter and bring back all rows along with a modified button caption, as shown below (also note that the value still exists in the textbox, but not applied as a filter):

Finally, you can get instantaneous results while you are typing inside the textbox with a small additional piece of code, as shown below:

Private Sub txtDeptFilter_TextChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.TextChangedEventArgs) Handles txtDeptFilter.TextChanged

If String.Compare(btnApplyFilter.Content.ToString(), "Clear Filter", StringComparison.OrdinalIgnoreCase) = 0 Then

oCvsEmp.View.Refresh()

End If

End Sub

My next article focuses on more features of the “CollectionViewSource” element. I hope you enjoyed the article; any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com

blog comments powered by Disqus
SILVERLIGHT ARTICLES

- With Silverlight Gone, Whither SharePoint?
- Silverlight in the News
- Silverlight Has a Bright Future
- Windows 8 Effects on .Net and Silverlight De...
- Microsoft`s SkyDrive Abandons Silverlight
- Silverlight Developers Unhappy with Windows ...
- Best Silverlight Examples
- How to install Silverlight for Windows Phone
- Microsoft Reveals Silverlight 5 Features
- Silverlight News: SRS and Microsoft to Bring...
- Silverlight 4.0: Paging Through Data using D...
- Silverlight 4.0: Navigating Data Using Domai...
- Silverlight 4.0: Filtering Data Using Domain...
- Silverlight 4.0: Sorting and Grouping Data w...
- Silverlight 4.0: Query Parameters of DomainD...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 5 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials