本例主要包含下列技巧:
1、动态产生Chart图形;
2、点击数据点DataPoint,响应selectChanged事件;
3、使用Style模板,动态设置DataPoint样式;
本例实现功能:
(1)程序加载后进入AreaChart显示数据,在同一坐标轴上显示两个Series图形。
(2)两Series分别使用不同的Y轴,鼠标悬停在数据点上方,ToolTip显示定制数据.
(3)点击AreaChart上的数据点,原Series变化为BubbleChart,显示DataPoint所在周7天的数据。
本例创建的工程是Silverlight Navigation Application类型的Project。
数据源为List类型,包含三个字段,测试本段代码时,如果没有数据库,可以用List.Add()方法手动加几个纪录。
public partial class Production
{
private DateTime DATE;
pirivate double GAS_HKT_SALES;
private double GAS_NAN_SALES;
}
一、Home.xaml前台
<navigation:Page xmlns:chartingToolkit="clr-namespace: System.Windows.Controls.DataVisualization.Charting;assembly=System.Windows.Controls.DataVisualization.Toolkit" x:Class="SilverlightChart1.Home"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"
Title="Home"
Style="{StaticResource PageStyle}">
<Grid x:Name="LayoutRoot">
<ScrollViewer x:Name="PageScrollViewer" Style="{StaticResource PageScrollViewerStyle}">
<StackPanel x:Name="ContentStackPanel">
<chartingToolkit:Chart x:Name="TestChart" Background= "AliceBlue" Height="600">
</chartingToolkit:Chart>
</StackPanel>
</ScrollViewer>
</Grid>
</navigation:Page>
二、在Assets/Styles.xaml中加一个新样式
<Style x:Key="AreaToolTipStyle2" TargetType="chartingToolkit:AreaDataPoint">
<Setter Property="Background" Value= "Orange" />
<Setter Property="BorderBrush" Value="Gray" />
<Setter Property="BorderThickness" Value="1" />
<Setter Property="IsTabStop" Value="False" />
<Setter Property="Width" Value="4" />
<Setter Property="Height" Value="4" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="chartingToolkit:AreaDataPoint">
<Grid x:Name="Root" Opacity="1">
<ToolTipService.ToolTip>
<StackPanel Margin="2,2,2,2">
<TextBlock Text="数量"></TextBlock>
<ContentControl Content="{TemplateBinding FormattedDependentValue}" />
<TextBlock Text="日期"></TextBlock>
<ContentControl Content="{TemplateBinding IndependentValue}" />
</StackPanel>
</ToolTipService.ToolTip>
<Ellipse StrokeThickness="{TemplateBinding BorderThickness}" Stroke="{TemplateBinding BorderBrush}" Fill="{TemplateBinding Background}"/>
</Grid>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
三、Home.xaml.cs后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using System.Windows.Shapes;
using SilverlightChart1.ServiceReference1;
using System.Windows.Controls.DataVisualization.Charting;
namespace SilverlightChart1
{
public partial class Home : Page
{
private List<ProductionData> tableList = new List<ProductionData>();
public Home()
{
InitializeComponent();
Service1Client client = new Service1Client("BasicHttpBinding_IService1");
client.GetAllCompleted += new EventHandler<GetAllCompletedEventArgs>(client_GetAllCompleted);
if (tableList.Count <=0)
{ client.GetAllAsync(); }
}
private void client_GetAllCompleted(object sender, GetAllCompletedEventArgs e)
{
tableList = e.Result.ToList<ProductionData>();
BindListProduction(tableList);// 绑定分页表的数据源
}
private void BindListProduction(List<ProductionData> list)
{
if (list != null)
{
#region 区域图
//设置图名称
TestChart.Title = "石油天然气产量、销量、消耗图";
//创建X轴
Action<Chart> chartModifier = (chart) =>
{
DateTimeAxis XAxis = new DateTimeAxis { Orientation = AxisOrientation.X, Title = "月份", FontStyle = FontStyles.Normal, FontSize = 8 };
XAxis.IntervalType = DateTimeIntervalType.Months;
XAxis.Interval = 1;
XAxis.ShowGridLines = true;
TestChart.Axes.Add(XAxis);
};
chartModifier(TestChart);
//创建Y轴1
LinearAxis YAxis1 = new LinearAxis { Orientation = AxisOrientation.Y, Location = AxisLocation.Right, Title = "天然气香港销量", ShowGridLines = false };
YAxis1.Orientation = AxisOrientation.Y;
TestChart.Axes.Add(YAxis1);
//创建数据系列,并绑定数据源
AreaSeries areaSeries1 = new AreaSeries();
areaSeries1.Title = "香港";
areaSeries1.ItemsSource = list;
areaSeries1.IndependentValueBinding = new System.Windows.Data.Binding("DATE");
areaSeries1.DependentValueBinding = new System.Windows.Data.Binding("GAS_HKT_SALES");
//设置DataPointStyle样式
areaSeries1.DataPointStyle = Application.Current.Resources["AreaToolTipStyle1"] as Style;
//areaSeries1所依赖的Y轴,不同Series可以依赖不同的Y轴,轴的数值范围等都可分别设置
areaSeries1.DependentRangeAxis = YAxis1;
//添加selectChanged事件响应方法
areaSeries1.IsSelectionEnabled = true;
areaSeries1.SelectionChanged += new SelectionChangedEventHandler(areaSeries1_SelectionChanged);
TestChart.Series.Add(areaSeries1);
//创建Y轴2
LinearAxis YAxis2 = new LinearAxis{ Orientation = AxisOrientation.Y, Location = AxisLocation.Left, Title = "天然气南山销量", ShowGridLines = false };
TestChart.Axes.Add(YAxis2);
//创建数据系列,并绑定数据源
AreaSeries areaSeries2 = new AreaSeries();
areaSeries2.Title = "南山";
areaSeries2.ItemsSource = list;
areaSeries2.IndependentValueBinding = new System.Windows.Data.Binding("DATE");
areaSeries2.DependentValueBinding = new System.Windows.Data.Binding("GAS_NAN_SALES");
//动态绑定DataPointStyle样式,该样式在Assets文件夹下的Styles.xaml文件中设置
areaSeries2.DataPointStyle = Application.Current.Resources["AreaToolTipStyle2"] as Style;
areaSeries2.DependentRangeAxis = YAxis2;
//添加selectChanged事件响应方法
areaSeries2.IsSelectionEnabled = true;
areaSeries2.SelectionChanged += new SelectionChangedEventHandler(areaSeries1_SelectionChanged);
TestChart.Series.Add(areaSeries2);
#endregion
}
}
//定义AreaChart的SelectionChanged事件的方法内容
private void areaSeries1_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
DataPointSeries dataPoint = (DataPointSeries)sender;
ProductionData selected = (ProductionData)dataPoint.SelectedItem;
DateTime date = (DateTime)selected.DATE;
DayOfWeek weekday = date.DayOfWeek;
DateTime startDate = new DateTime();
DateTime endDate = new DateTime();
//自定义函数计算当前日期所在周的Monday到Sunday日期
getStartEndDate(date, ref startDate, ref endDate);
List<ProductionData> tempList = new List<ProductionData>();
//在数据源List中选出当前点击的DataPoint日期所在周的数据,存入一个List类型的tempList中
foreach (ProductionData p in tableList)
{
if (p.DATE >= startDate && p.DATE <= endDate)
{
tempList.Add(p);
}
}
TestChart.Axes.Clear();
TestChart.Series.Clear();
//创建X轴
Action<Chart> chartModifier = (chart) =>
{
DateTimeAxis XAxis = new DateTimeAxis { Orientation = AxisOrientation.X, Title = "日期", FontStyle = FontStyles.Normal, FontSize = 8, Minimum =startDate.AddDays(-1), Maximum =endDate.AddDays (1) };
XAxis.IntervalType = DateTimeIntervalType.Days;
XAxis.Interval = 1;
XAxis.ShowGridLines = true;
TestChart.Axes.Add(XAxis);
};
chartModifier(TestChart);
//气泡图
BubbleSeries bubbleSeries1 = new BubbleSeries();
bubbleSeries1.ItemsSource = tempList;
bubbleSeries1.IndependentValueBinding = new System.Windows.Data.Binding("DATE");
bubbleSeries1.DependentValueBinding = new System.Windows.Data.Binding("GAS_HKT_SALES");
bubbleSeries1.Title = "香港销售量";
TestChart.Series.Add(bubbleSeries1);
BubbleSeries bubbleSeries2 = new BubbleSeries();
bubbleSeries2.ItemsSource = tempList;
bubbleSeries2.IndependentValueBinding = new System.Windows.Data.Binding("DATE");
bubbleSeries2.DependentValueBinding = new System.Windows.Data.Binding("GAS_NAN_SALES");
bubbleSeries2.Title = "南山销售量";
TestChart.Series.Add(bubbleSeries2);
}
//自定义函数,参数为:当前日期date,所在周起始日期startDate,所在周终了日期endDate
private void getStartEndDate( DateTime date, ref DateTime startDate, ref DateTime endDate)
{
DayOfWeek weekday = date.DayOfWeek;
switch (weekday)
{
case DayOfWeek.Monday:
{
startDate = date;
endDate = date.AddDays(6);
break;
}
case DayOfWeek.Tuesday:
{
startDate = date.AddDays(-1);
endDate = date.AddDays(5);
break;
}
case DayOfWeek.Wednesday:
{
startDate = date.AddDays(-2);
endDate = date.AddDays(4);
break;
}
case DayOfWeek.Thursday:
{
startDate = date.AddDays(-3);
endDate = date.AddDays(3);
break;
}
case DayOfWeek.Friday:
{
startDate = date.AddDays(-4);
endDate = date.AddDays(2);
break;
}
case DayOfWeek.Saturday:
{
startDate = date.AddDays(-5);
endDate = date.AddDays(1);
break;
}
case DayOfWeek.Sunday:
{
startDate = date.AddDays(-6);
endDate = date;
break;
}
default:
{
startDate = date;
endDate = date;
break;
}
}
}
// Executes when the user navigates to this page.
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
}
}