Log in to like this post! Sparkline integrated in WPF Data Grid Damyan Petev / Wednesday, February 22, 2012 This post is kind of a follow up, part two if you will, on integrating the XamSparkline – a XAML cross-platform control part of both NetAdvantage for WPF and Silverlight Data Visualization packages – into Infragistics grids’ cells. If this is your first meeting with this neatly fitting, data-intensive control - make sure you start with Atanas Dyulgerov’s Introduction to the Infragistics Sparkline Control blog post. And if you missed my first post, you can click to read about integrating the Sparkline in a XamGrid. With that said, you should be aware it’s no pain to incorporate the XamSparkline in a XamGrid which made for a quite easy implementation with code that is even easier to transfer between platforms. And even so, this is far from enough. We now turn attention to those who went “But we already have a huge project with the XamDataGrid instead!” or “We just like the other grid better, have you forgotten about it?”. And we hear you – as it will now be demonstrated it’s not much of an issue to use the Sparkline in the WPF-Only data grid, too. Seeing as this is the second blog post on that subject I would like to remind of our little scenario – the goal is display hierarchical data, but in the same time provide extremely important information from the child records in the parent row for very quick reference and to do that we settled on using visual representation (the XamSparkline) to provide the users with the ability to instantly spot odd values or trends. And again there is a teaser screenshot: This time we would provide freight expenses for each customer with the idea that the user should be able to see any too sudden changes in their orders. Preparations Once more - no difference when it comes to the products – a combination of NetAdvantage for WPF Line of Business and Data Visualization, which essentially means you will need at least trial versions of both. In terms of data, as the finer points of the XamDataGrid and not the focus of this post, we can again rely of the Help Topics to provide fast-starter solution with the SampleDataUtil class. You can pick between C# and VB.NET implementations of this class and it will give you easy data access, only assuming you have the Northwind sample database. Should a different method be required or just better suits your taste, you can always find information on Accessing Data using the XamDataGrid Help Topics. As always a list of assemblies and namespaces to be added to your project. In you XAML add the following namespaces: xmlns:ig="http://schemas.infragistics.com/xaml" xmlns:igDP="http://infragistics.com/DataPresenter" First one is where all the shared XAML controls from Infragistics are (including the XamSparkline) and the second one as it’s name suggests – is for the XamDataGrid, which is a part of the xamDataPresenter™ control family. Then come the assemblies to reference - starting with the base InfragisticsWPF4.v11.2.dll, then InfragisticsWPF4.Editors.v11.2.dll and InfragisticsWPF4.DataPresenter.v11.2.dll required by the data Grid and finally the InfragisticsWPF4.Controls.Charts.XamSparkline.v11.2.dll for the sparkline itself. When that is done you are ready to add a XamDataGrid to your XAML and also add a handle for the Windows’s Loaded event while at it: <Window Loaded="Window_Loaded" <!--...--> <igDP:XamDataGrid x:Name="XamDataGrid" InitializeRecord="XamDataGrid_InitializeRecord"> <!--To do: Add Field Layout--> </igDP:XamDataGrid> Now in the code behind once the Window is loaded we will provide data to the grid using the functionality provided for us by the data access class mentioned earlier. Since I have Northwind on my SQLExpress instance, the parameter to pass would be set to that with the standard “.\” which is the equivalent of localhost: private void Window_Loaded(object sender, RoutedEventArgs e) { //Create a DataSet from Northwind's Customers and Orders: System.Data.DataSet customerDS = SampleDataUtil.GetCustomersOrders(".\\SQLExpress"); if (customerDS.Tables["Customers"] != null) { //and if available set it as data source to the grid this.XamDataGrid.DataSource = customerDS.Tables["Customers"].DefaultView; } } Now to we would need to add a custom column for our sparklines and of course provide them with data. In my case the data doesn’t have a field with a value collection so I will make myself one, but in case you have data that is already fit to be presented by the chart control – by all means, feel free to skip the next part. As you may have noticed in the definition above there is a handle defined for the InitializeRecord event. We will use that to go through the records and provide data for the cells where the sparkline would be. But first we will add that custom column to the XamDataGrid, which in our case would be an Unbound Field added to the grid’s layouts : <igDP:XamDataGrid.FieldLayouts> <igDP:FieldLayout > <igDP:FieldLayout.Fields> <!--Unbound field definition:--> <igDP:UnboundField Name="Chart" Label="Freight expenses"/> <!--End of Unbound field definition--> <!-- Below column definitions are optional as they match the data set and can be auto-generated in case you skip them. Leaving them makes for better custom labels. --> <igDP:Field Name="CustomerID" Label="Customer ID" /> <igDP:Field Name="CompanyName" Label="Company Name" /> <igDP:Field Name="ContactName" Label="Contact Name" /> <igDP:Field Name="Address" Label="Address" /> <igDP:Field Name="City" Label="City" /> <igDP:Field Name="Region" Label="Region" /> <igDP:Field Name="PostalCode" Label="Postal Code" /> <igDP:Field Name="Country" Label="Country" /> <igDP:Field Name="Phone" Label="Phone" /> <igDP:Field Name="Fax" Label="Fax" /> <igDP:Field Name="ContactTitle" Label="Contact Title" /> </igDP:FieldLayout.Fields> </igDP:FieldLayout> </igDP:XamDataGrid.FieldLayouts> The name of the field is ‘Chart’ and we can now use that to set its data in code upon row initializations: private void XamDataGrid_InitializeRecord(object sender, InitializeRecordEventArgs e) { if (e.Record is DataRecord) { //get the data record and verify it is a parent row: DataRecord dr = (DataRecord)e.Record; if (dr.HasExpandableFieldRecords) { List<int> values = new List<int>(); foreach (ExpandableFieldRecord row in dr.ChildRecords) { RecordCollectionBase recColBase = row.ChildRecords; //go through all the child records foreach (Record childRec in recColBase) { //and build value collections with Freight expenses for each: values.Add((int)double.Parse((childRec as DataRecord).Cells["Freight"].Value.ToString())); } //build nice parsable string with the values: StringBuilder sb = new StringBuilder(); values.ForEach( delegate(int value) { sb.Append(value.ToString() + " "); }); // set that string as value of the parent's Chart cell dr.Cells["Chart"].Value = sb.ToString(); } } } } At this point you should have an application with hierarchical XamDataGrid with an extra column in the parent rows containing a set of freight values. Now what is left to do is to turn those cells into XamSparkline controls! Adding the Sparkline The basic idea behind this is that the values for each cell have display objects called Cell Value Presenters and you can override their template. What would then be left is to set it to a Control Template with a Sparkline and bind it to the cell’s value. That of course might require a converter, so you can start by adding that in a new class implementing the IValueConverter interface. In it we’ll parse the string values to integers and return a list with their values. This is how the code for that looks like: class SourceConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { //skip the first (header) cell if ((value as CellValuePresenter).Record.DataItemIndex != -1) { //get the value, split it and parse each to int string values = (string)(value as CellValuePresenter).Record.Cells["Chart"].Value; List<int> convertedValues = new List<int>(); List<string> separates = values.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); convertedValues = separates.ConvertAll(x => int.Parse(x)); //return the list with int values: return convertedValues; } return null; } public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } And the next logical step would be to add that as a resource in a proper scope in your XAML, like so: <local:SourceConverter x:Key="sourceConverter" /> The Item source of the XamSparkline will be bound to its templated parent which in our case is the Cell Value Presenter and this is why the passed value to the converter above is treated as such. It’s all very convenient as it not only provides a Record object, whose index we can check in order to skip the header (-1) row, but also exposes a Cells collection for us to grab values from. Now once you have that final piece in place you can override the presenter’s template. You can do that by defining the style as a resource or within the Unbound field definition, that is up to you and here is the general outline of the style itself – just remember to add a key if you define it as a resource: <Style TargetType="{x:Type igDP:CellValuePresenter}"> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}"> <ig:XamSparkline ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource sourceConverter}}" NormalRangeVisibility="Visible" NormalRangeMinimum="0" NormalRangeMaximum="50" NormalRangeFill="GreenYellow" HighMarkerVisibility="Visible" LowMarkerVisibility="Visible" ValueMemberPath="" Width="150" Height="40" /> </ControlTemplate> </Setter.Value> </Setter> </Style> This is the full code for the XamDataGrid with all the changes so far (points of interest are marked with comments): <igDP:XamDataGrid x:Name="XamDataGrid" InitializeRecord="XamDataGrid_InitializeRecord"> <igDP:XamDataGrid.FieldLayouts> <igDP:FieldLayout > <igDP:FieldLayout.Fields> <!--Unbound field definition:--> <igDP:UnboundField Name="Chart" Label="Freight expenses"> <igDP:UnboundField.Settings> <igDP:FieldSettings> <igDP:FieldSettings.CellValuePresenterStyle> <!--Style template definition:--> <Style TargetType="{x:Type igDP:CellValuePresenter}"> <Setter Property="OverridesDefaultStyle" Value="True"/> <Setter Property="Template"> <Setter.Value> <ControlTemplate TargetType="{x:Type igDP:CellValuePresenter}"> <ig:XamSparkline ItemsSource="{Binding RelativeSource={RelativeSource TemplatedParent}, Converter={StaticResource sourceConverter}}" NormalRangeVisibility="Visible" NormalRangeMinimum="0" NormalRangeMaximum="50" NormalRangeFill="GreenYellow" HighMarkerVisibility="Visible" LowMarkerVisibility="Visible" ValueMemberPath="" Width="150" Height="40" /> </ControlTemplate> </Setter.Value> </Setter> </Style> <!--End of Style template definition--> </igDP:FieldSettings.CellValuePresenterStyle> </igDP:FieldSettings> </igDP:UnboundField.Settings> </igDP:UnboundField> <!--End of Unbound field definition--> <!-- Below column definitions are optional as they match the data set and can be auto-generated in case you skip them. Leaving them makes for better custom labels. --> <igDP:Field Name="CustomerID" Label="Customer ID" /> <igDP:Field Name="CompanyName" Label="Company Name" /> <igDP:Field Name="ContactName" Label="Contact Name" /> <igDP:Field Name="Address" Label="Address" /> <igDP:Field Name="City" Label="City" /> <igDP:Field Name="Region" Label="Region" /> <igDP:Field Name="PostalCode" Label="Postal Code" /> <igDP:Field Name="Country" Label="Country" /> <igDP:Field Name="Phone" Label="Phone" /> <igDP:Field Name="Fax" Label="Fax" /> <igDP:Field Name="ContactTitle" Label="Contact Title" /> </igDP:FieldLayout.Fields> </igDP:FieldLayout> </igDP:XamDataGrid.FieldLayouts> </igDP:XamDataGrid> And the end result looks like this: We have a normal range of up to 50 for freight expenses and you can easily tell that while some hold their values close or even below, there are users such as ‘BERGS’ that have very high values that might need some further investigation. Conclusion Again how you define the XamSparkline in the template is up to you – all you need in the proper data, a field to set the template of and an optional converter (depending on your data). Simple as that, you have now seen how to integrate the this control in both the cross-platform XamGrid and the WPF specific XamDataGrid with limited effort and tremendous outcome! The obligatory calling - check out the Silverlight Data Visualization Samples online or download the local WPF Samples. Also download the demo project where you will find another style setup available(with columns as display type and the nice blue trendline) and since curiosity is such a nice thing to appeal to, here a teaser screenshot for that one too: The solution has been cleaned, so make sure assembly references are all in check and build.