Introduction

In our last post, we discussed how to display contacts in Conference Buddy with data serialized as JSON. We looked at two new controls that we haven’t seen yet, RadDataBoundListBox and RadExpander. Using both of these controls, we were able to create an elegant user interface with little effort.

In this post, we are going to display data coming from a particular event into RadChart. We are going to add a Pie Chart to display the total number of contacts requesting follow ups. It will also show those that do not want follow ups.

Initial Setup

I’m going to assume your development environment is setup and RadControls for Windows Phone 8 is installed. If you don’t have them yet then you can be downloaded from your account. The completed source code for the section can be found here.

Continuing with Contact Details

After examining our JSON file in the previous blog post, it became obvious that each contact would need to be associated with an event. So let’s take a look at our sample data now with an event id added in. You can see it clearly marked in red, but also pay special attention to the “Request” data in green as this will be used in our Pie Chart to quickly see who wants to be contacted after the event is over.

[
   {
      "EventId":1,
      "Email":"michael.crump@telerik.com",
      "FirstName":"Michael",
      "LastName":"Crump",
      "Title":"Mr",
      "Company":"Telerik",
      "PhoneNumber":"205-888-8888",
      "Notes":"",
      "RegisterForRaffle":false,
      "ReceiveDevToolsUpdates":true,
      "ReceiveAlmUpdates":true,
      "ReceiveTestingUpdates":false,
      "ReceiveHtml5Updates":false,
      "RequestForContact":false,
      "RequestSuggestion":true,
      "ProblemReport":false,
      "Other":false,
      "RequestProduct":"Windows 8",
      "RequestSubject":"Subject1"
   },
   {
      "EventId":1,
      "Email":"testemail@testemail.com",
      "FirstName":"Ridley",
      "LastName":"Crump",
      "Title":"Mr",
      "Company":"Telerik",
      "PhoneNumber":"205-888-8888",
      "Notes":"Note2",
      "RegisterForRaffle":true,
      "ReceiveDevToolsUpdates":false,
      "ReceiveAlmUpdates":false,
      "ReceiveTestingUpdates":false,
      "ReceiveHtml5Updates":true,
      "RequestForContact":false,
      "RequestSuggestion":false,
      "ProblemReport":false,
      "Other":false,

      "RequestProduct":"Windows Phone 8",
      "RequestSubject":"Subject1"
   }
]

Note that Michael Crump request a follow up whereas Ridley Crump does not.

Finishing up our UI by adding a new PivotItem to ListCustomer.xaml

Heading back over to our /Views/ListCustomer.xaml page, we will add in our second PivotItem to the Page. You can simply scroll right underneath the first pivot and paste in the following code snippet:

<!--Pivot item two-->
<phone:PivotItem Header="follow ups">
 
 <Grid>
 <Grid.RowDefinitions>
 <RowDefinition Height="Auto" />
 <RowDefinition Height="*" />
 <RowDefinition Height="*"/>
 </Grid.RowDefinitions>
 
 <TextBlock x:Name="txtTotalContacts" Text="CONTACTS" Grid.Row="0" HorizontalAlignment="Center" Style="{StaticResource PhoneTextExtraLargeStyle}" />
 
 <telerikChart:RadPieChart x:Name="chart" Grid.Row="1" Margin="0,0,0,180" Grid.RowSpan="2">
 <telerikChart:PieSeries>
 <telerikChart:PieSeries.SliceStyles>
 <Style TargetType="Path">
 <Setter Property="Fill" Value="Blue"/>
 </Style>
 <Style TargetType="Path">
 <Setter Property="Fill" Value="Red"/>
 </Style>
 </telerikChart:PieSeries.SliceStyles>
 <telerikCharting:PieDataPoint Value="50"/>
 <telerikCharting:PieDataPoint Value="50"/>
 </telerikChart:PieSeries>
 </telerikChart:RadPieChart>
 <StackPanel Orientation="Vertical" Grid.Row="2" Margin="0,149,0,0">
 
 <TextBlock x:Name="txtWithFollowUp" Text="0 WITH FOLLOW UP" Foreground="Red" HorizontalAlignment="Center" Margin="10" FontSize="30"/>
 <TextBlock x:Name="txtWithoutFollowUp" Text="0 WITHOUT FOLLOW UP" Foreground="Blue" HorizontalAlignment="Center" Margin="10" FontSize="30"/>
 </StackPanel>
 </Grid>
 
</phone:PivotItem>

As you can see from looking at the code snippet listed above, we have added 3 simple TextBlocks to count the total number of contacts at a given event, count the number of those requesting a follow up and those that chose not to be contacted.

You will also find the RadPieChart, which we will create an instance of PieSeries. In this example, we are creating two halves, one is blue and the other is red. This will let our evangelist visualize the data quickly and easily. We have also added in sample data by declaring two PieDataPoint. This will allow us to get a glimpse of what our data will look like in the Visual Studio designer. The PieSeries demonstrated here is just one sample of many that RadChart is capable of doing.

Switching Over to ListCustomer.xaml.cs

We already have our MainViewModel created as well as the DataContext set to the current instance of the ViewModel. The only part that I’ve refactored out was populating events shown in the RadListPicker on the first contact page to the ViewModel. I’ve also attached an event handler to our SelectionChanged event to populate the customers depending on which event is selected. Our SelectionChanged event looks like the following:

private void rlpEventName_SelectionChanged(object sender, SelectionChangedEventArgs e)
  {
      _vm.PopulateCustomersById(rlpEventName.SelectedIndex);
  }

Inside of the MainViewModel.cs file, you will find the PopulateCustomersById method as shown below:

public async void PopulateCustomersById(int id)
{
      var json=await ReadFromFile("mycontacts.json");
      IList<Customer> eventsFromJson=JsonConvert.DeserializeObject<List<Customer>>(json);
      ObservableCollection<Customer> customers=new ObservableCollection<Customer>(eventsFromJson);
      var matchingCustomers=new ObservableCollection<Customer>(customers.Where(d => d.EventId == id));
      Customers=matchingCustomers;
}
 
public async Task<string> ReadFromFile(string filename)
{
 string json=String.Empty;
 
    IsolatedStorageFile myIsolatedStorage=IsolatedStorageFile.GetUserStoreForApplication();
    IsolatedStorageFileStream fileStream=myIsolatedStorage.OpenFile(filename, FileMode.OpenOrCreate, FileAccess.ReadWrite);
 
 using (StreamReader streader=new StreamReader(fileStream))
   {
        json=streader.ReadToEnd();
   }
 return json;
}

The PopulateCustomersById method expects an id to determine which customers should be displayed in the RadDataBoundListBox. Again, it is simply going out to IsolatedStorage and retrieving the file where the EventId equals the id being passed in. Now our Customers property is set with only valid data from that particular event.

Now that the data is available inside of our ViewModel, we can display the appropriate data on our new PivotItem page we created earlier with the following code:

public void pvt_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
 switch (pvt.SelectedIndex)
    {
 case 0:
 break;
 case 1:
 //Second Pivot Item
       txtTotalContacts.Text=_vm.Customers.Count.ToString() + " CONTACTS";
 int i=0;
 foreach (var item in _vm.Customers)
       {
 if (new[]
            {
                 item.RequestForContact,
                 item.RequestSuggestion,
                 item.ProblemReport,
                 item.Other
             }.Contains(true))
             {
                i++;
             }
             }
             txtWithFollowUp.Text=i.ToString() + " WITH FOLLOW UP";
 int withoutfollowup=_vm.Customers.Count - i;
             txtWithoutFollowUp.Text=withoutfollowup.ToString() + " WITHOUT FOLLOW UP";
 this.chart.Series[0].ItemsSource=new double[]
             {
                  withoutfollowup,
                  i
             };
 break;               
    }
  }

After the user switches to the second PivotItem, then we can easily display the appropriate counts by relying on our Customers ViewModel and LINQ. The chart is populated by calling the ItemSource property and provided an array of doubles. One is those without follow ups and the other is those with follow ups. Below you will see our contact list in Figure 1 and our pie chart in Figure 2.

1

Figure 1: The contact list pivotitem with the ability to select an event.

2

Figure 2: The follow ups page with RadChart displaying those with or without a follow up.

Conclusion

Wow, so far we have used 4 Telerik controls in just this one page, RadListPicker, RadDataBoundListBox , RadExpander and RadChart! We saw just how easy it was to add charting capabilities by declaring our chart in XAML and reading data out of a JSON file in IsolatedStorage to populate it. We also saw that the chart support design time data as well as it supports many other chart types.

Stay tuned for the next article as we will begin adding our events page and I’ll expose you to several controls that you have not seen yet such as: RadTextBox , RadDatePicker and RadHubTile.

As always, the source code to this project is available here and if you have any questions, then just let me know.

I know I remind you every single post, but the Nokia premium developer program allows you to get RadControls for Windows Phone for free and they have a lot of additional resources to help you get started.

-Michael Crump (@mbcrump)

 Webinar Registration


MichaelCrump
About the Author

Michael Crump

is a Microsoft MVP, Pluralsight and MSDN author as well as an international speaker. He works at Telerik with a focus on everything mobile.  You can follow him on Twitter at @mbcrump or keep up with his various blogs by visiting his Telerik Blog or his Personal Blog.

Related Posts

Comments