OnLoad Animations
For example, the code below creates a 'fade-in' animation that causes each point in the data series to slowly appear, building the chart gradually:
void AnimateChart()
{
// Build chart as usual
SalesPerRegionAreaStacked_Click(this, null);
// Make all series transparent and attach event handler
// to make them visible gradually
foreach (DataSeries ds in _c1Chart.Data.Children)
{
ds.Opacity = 0;
ds.Loaded += ds_Loaded;
}
}
The code starts by generating a chart as usual, and then loops through the DataSeries setting their Opacity to zero. This way, the chart will appear blank when it loads.
The code also attaches a handler to the Loaded event. This is where the animations will be added to each PlotElement. Here is the implementation:
// Animate each PlotElement after it has been loaded
void ds_Loaded(object sender, EventArgs e)
{
PlotElement plotElement = sender as PlotElement;
if (plotElement != null)
{
// Create storyboard to animate PlotElement
Storyboard sb = new Storyboard();
Storyboard.SetTarget(sb, plotElement);
// Add Opacity animation to storyboard
DoubleAnimation da = new DoubleAnimation();
da.SetValue(Storyboard.TargetPropertyProperty, new PropertyPath("Opacity"));
da.Duration = new Duration(TimeSpan.FromSeconds(2));
da.To = 1;
sb.Children.Add(da);
// Offset BeginTime for each series and point within series
double seconds = 2;
var dp = plotElement.DataPoint;
if (dp != null && dp.PointIndex > -1)
{
seconds = dp.SeriesIndex + dp.PointIndex * 0.1;
}
da.BeginTime = TimeSpan.FromSeconds(seconds);
// Start storyboard
sb.Begin();
}
}
This event handler gets called once for each PlotElement that is generated. The code creates a Storyboard object for each PlotElement and uses it to gradually change the opacity of the element from zero to one (completely transparent to completely solid).
Notice how the code uses the DataPointproperty to determine which series and which data point the plot element belongs to, and then sets the BeginTime property of the animation to cause each plot element to become visible at different times. This way, the points appear one at a time, instead of all at once.
Notice also that the code tests the PointIndex property to make sure it is greater than -1. This is because some plot elements do not correspond to individual points, but rather to the whole series. This is the case for Area elements for example.
This code can be used for all chart types. You can use it to slowly show plot symbols, lines, pie slices, and so on.