As you know, it is easy to extend the user interface of screens in LightSwitch applications by adding custom Silverlight controls. The Silverlight Toolkit adds to your toolbox a number of new useful controls, especially for data visualization such as charts. In this post I will show you how to add a Pie Chart to a screen listing products.
Imagine you have an entity named Product, like the following which I grabbed from the Northwind database:
Once you have this entity, imagine you also have a Search Screen pointing to the Products collection. Since the list of products is quite long, we can restrict it by applying the following query to the screen:
Now add to the solution a new project of type Silverlight Class Library. I assume you already performed these steps before, so I will not describe them in details. Remove the Class1.vb code file added by default and then add a new Silverlight User Control item to the project, calling it ProductsChartControl. The goal is displaying in the charts products by unit price. When the designer is ready, edit the default Grid container by adding the chart as follows:
<Grid x:Name="LayoutRoot" Background="White">
<toolkit:Chart x:Name="unitsInStockChart" Background="Yellow" BorderBrush="Green" BorderThickness="2"
Title="Situation of products in stock" Grid.Column="0" >
<toolkit:Chart.Series>
<toolkit:PieSeries Name="PieSeries1" ItemsSource="{Binding Screen.ProductCollection}" IsSelectionEnabled="False"
IndependentValueBinding="{Binding ProductName}" DependentValueBinding="{Binding UnitPrice}" />
</toolkit:Chart.Series>
</toolkit:Chart>
</Grid>
Notice that it is a good idea dragging chart controls from the toolbox so that all the required references and XML namespaces are added for you. The chart is populated via the ItemsSource property assignment which points to the Screen.ProductCollection. Then the IndependentValueBinding property is related to the Y axis, while DependentValueBinding populates the pie chart. Build the project and then go back to the screen designer. Select the Vertical Stack|Search Product root element and then click Add Layout Item|Custom User Control. You will be asked to specify a new control, so click Add Reference and select the newly created user control:
Now run the application and run the search screen. As you can see the pie chart is populated via data-binding correctly:
This is a nice way to improve the way LightSwitch applications show data!
Alessandro