Thursday, September 24, 2015

Displaying, and animating, ListBoxItem content as pie chart

On a recent project, it was requested to have the different values presented to a user not only displayed as a pie chart - but to have the pie chart animate to the appropriate value. Sounds easy enough, but Storyboards don't play nice with bindings. At least, not in XAML - so I had to dive into C# to accomplish the desired result.

The first step was to go ahead and create a UserControl with DependencyProperties and location for the Storyboard associated with this particular element. I created three properties : DisplayEndAngle, DisplayChartColor and PieChartOrder.

DisplayEndAngle is for the actual value of the chart, that has gone through a converter to determine the correct EndAngle value to be used by the Arc control.

DisplayChartColor allows me to customize the color of the Arc stroke, and change it in the ListBox's Selected state.

PieChartOrder - I gave each ListBoxItem a name, and used that to determine the start time of the Arc's animation sequence.

I used this forum post as a springboard for the codebehind.



This ended up to be one of the few controls where I ended up writing more codebehind than I did XAML for it to work correctly. Using a switch statement I was able to use the Name and assign the appropriate BeginTime and KeyTimes required. In the actual XAML, I didn't assign the EndAngle a value, every time I did it would show with that value, disappear and then animate. By just using the codebehind for the value binding I was still able to display the correct information.

For this demo, I didn't use a ResourceDictionary for the templates and styles - but simply defined them in the UserControl.Resources. This includes the reference to the converter used to make sure the Arc displays the correct value: PercentToAngleConverter.





Using RelativeSource bindings, I found it easier to set the color of the Arc and even change it in the Selected state of the ListBoxItem.



And, when I run it :) each of the elements animates in sequence to the correct value.



No comments:

Post a Comment