silverlight图表:使用Silverlight Toolkit绘制图表(上)--柱状图

  本文举例源代码或素材下载

  Silverlight Toolkit提供了绘制柱状图(Column,Bar)饼图(Pie)折线图(Line), 散点图(Scatter)等Control控件

  我们可以很方便将已有数据源绑定到相应图形Control控件上设置好相应X,Y轴显示样式和数据字段的后就大功告

  成了同时其还支持图形定时加载刷新图形动态加载动画效果今天就先以柱状图为例简要整理总结下如

  何使用该Control控件来显示我们数据   首先我们需要创建个Silverlight项目命名为:DataVisualization

  然后我们使用WCF方式发布数据源信息这里我们创建个"Silverlight功能WCF"并将其命名为:

  DataService.svc

使用Silverlight Toolkit绘制图表(上)--柱状图

  接着将下面代码拷贝到该类文件中:

publicEmployeeInfo
{
  publicEmployeeID{;get;}
  publicEmployeeName{;get;}
  publicSalary{;get;}
  publicCost{get;;}
  publicCity{;get;}
} 
 
[ServiceContract(Namespace="")]
[AspNetCompatibilityRequirements(RequirementsMode=AspNetCompatibilityRequirementsMode.Allowed)]
publicDataService
{
  [OperationContract]
  publicList<EmployeeInfo>GetEmployeeList
  {
    List<EmployeeInfo>employeeList=List<EmployeeInfo>;
    employeeList.Add(EmployeeInfo{EmployeeID=1,EmployeeName="张 3",Salary=1000,City="合肥"});
    employeeList.Add(EmployeeInfo{EmployeeID=2,EmployeeName="李 4",Salary=1500,City="天津"});
    employeeList.Add(EmployeeInfo{EmployeeID=3,EmployeeName="王 5",Salary=2000,City="上海"});
    employeeList.Add(EmployeeInfo{EmployeeID=4,EmployeeName="赵 6",Salary=-800,City="北京"});
    employeeList.Add(EmployeeInfo{EmployeeID=5,EmployeeName="尤 7",Salary=2100,City="武汉"});
    employeeList.Add(EmployeeInfo{EmployeeID=6,EmployeeName="马 8",Salary=2300,City="海口"});
    employeeList;
  }
}


  这里数据源我们就创建完成了它将会返回6个雇员信息

  下面我们往该Silverlight应用Xaml文件上拖(或手工声明)个ChartControl控件如下: 

<charting:ChartTitle="员工薪水"x:Name="EmployeeChart"></charting:Chart>

  我们看到在该Control控件上我们指定了Title信息该信息会显示在图表最上方

  下面开始编写CS代码

  1.首先我们向该Silverlight应用中添加对刚才声明WCF引用

  2.使用WCF生成客户端类来获取相应数据源代码如下:

voidLoadWcfData
{
  dataServiceClient.GetEmployeeListCompletedEventHandler<GetEmployeeListCompletedEventArgs>(dataServiceClient_GetEmployeeListCompleted);
  dataServiceClient.GetEmployeeListAsync;
}


  3.将WCF返回数据源信息绑定到相应图形Control控件上化该Control控件相应信息如下:

voiddataServiceClient_GetEmployeeListCompleted(objectsender,GetEmployeeListCompletedEventArgse)
{
  ObservableCollection<EmployeeInfo>employeeList=e.Result;
  Action<Chart>chartModier=(chart)=>
  {
    AxisdateAxis=Axis{Orientation=AxisOrientation.Horizontal,Title="雇员名称",FontStyle=FontStyles.Normal,FontSize=12f,ShowGridLines=true};
    EmployeeChart.Axes.Add(dateAxis);
    AxisvalueAxis=Axis{Orientation=AxisOrientation.Vertical,Title="薪水",Minimum=-1000,Maximum=3000,ShowGridLines=true};
    EmployeeChart.Axes.Add(valueAxis);
  };
  chartModier(EmployeeChart);
  ColumnSeriesseries=ColumnSeries;
  series.ItemsSource=employeeList;
  series.IndependentValueBinding=.Windows.Data.Binding("EmployeeName");
  series.DependentValueBinding=.Windows.Data.Binding("Salary");
  series.Title="薪水";
  EmployeeChart.Series.Add(series);
}


  在上面代码中我们创建了Axis对象用以将X,Y轴描述信息绑定到指定图形Control控件上然后将我们指定数据

  源绑定到该图形Control控件ItemsSource属性上最后再绑定两个座标轴要显示相应数据:

  X轴: series.IndependentValueBinding = .Windows.Data.Binding("EmployeeName");

  Y轴: series.DependentValueBinding = .Windows.Data.Binding("Salary");

  下面我们来看下最终显示效果如下图所示:

使用Silverlight Toolkit绘制图表(上)--柱状图

  大家看到在Y轴上我们既显示了正轴也显示了负轴这就是通过Minimum = -1000, Maximum = 3000这

  设置实现 

  还不错了到这里我们只是简要领略了个图形Control控件基本功能接着我们再了解下它还有那些更高级使

  用窍门技巧

  首先是图形定时加载刷新要实现这个演示我们需要个实时变化数据源以便当我们定时刷新Control控件时能

  显示区别数据信息所以我们要在WCF中创建个这样数据源:

[OperationContract]
publicList<EmployeeInfo>GetEmployeeDynamicList
{
  Randomrandom=Random;
  List<EmployeeInfo>employeeList=List<EmployeeInfo>;
  employeeList.Add(EmployeeInfo{EmployeeID=1,EmployeeName="张 3",Salary=random.Next(500,3000),City="合肥"});
  employeeList.Add(EmployeeInfo{EmployeeID=2,EmployeeName="李 4",Salary=random.Next(500,3000),City="天津"});
  employeeList.Add(EmployeeInfo{EmployeeID=3,EmployeeName="王 5",Salary=random.Next(500,3000),City="上海"});
  employeeList.Add(EmployeeInfo{EmployeeID=4,EmployeeName="赵 6",Salary=random.Next(500,3000),City="北京"});
  employeeList.Add(EmployeeInfo{EmployeeID=5,EmployeeName="尤 7",Salary=random.Next(500,3000),City="武汉"});
  employeeList.Add(EmployeeInfo{EmployeeID=6,EmployeeName="马 8",Salary=random.Next(500,3000),City="海口"});
  employeeList;
}


  大家看到这里使用了Random来模拟个动态数据源信息其生成随机数介于500-3000的间那么接下来

  们再SilverlightXAML上创建这样个Chart对象用以显示该动态数据源信息如下:  

<charting:ChartTitle="动态员工薪水"x:Name="DynamicEmployeeChart"/>

  接着就是相应CS代码了这里为了方便起见这里直接使用DispatcherTimer来定时(3秒)获取相应数据源信

  息如下:

voidLoadDynamicData
{
  .Windows.Threading.DispatcherTimerdispatcherTimer=.Windows.Threading.DispatcherTimer;
  dispatcherTimer.Interval=TimeSpan.FromSeconds(3);
  dispatcherTimer.Tickdelegate
  {       
    dataServiceClient.GetEmployeeDynamicListCompletedEventHandler<GetEmployeeDynamicListCompletedEventArgs>(dataServiceClient_GetEmployeeDynamicListCompleted);
    dataServiceClient.GetEmployeeDynamicListAsync;
  };
  dispatcherTimer.Start;
}


  接着就是化相应图形Control控件并绑定相应数据源了代码和上面CS代码相似如下:

voiddataServiceClient_GetEmployeeDynamicListCompleted(objectsender,GetEmployeeDynamicListCompletedEventArgse)
{
  ObservableCollection<EmployeeInfo>employeeList=e.Result;
  DynamicEmployeeChart.Axes.Clear;
  DynamicEmployeeChart.Series.Clear;
  Action<Chart>chartModier=(chart)=>
  {
    AxisdateAxis=Axis{Orientation=AxisOrientation.Horizontal,Title="雇员名称",FontStyle=FontStyles.Normal,FontSize=12f,ShowGridLines=true};
    DynamicEmployeeChart.Axes.Add(dateAxis);
    AxisvalueAxis=Axis{Orientation=AxisOrientation.Vertical,Title="薪水",Minimum=0,Maximum=3000,ShowGridLines=true};
    DynamicEmployeeChart.Axes.Add(valueAxis);
  };
  chartModier(DynamicEmployeeChart);
  ColumnSeriesseries=ColumnSeries;
  series.ItemsSource=employeeList;
  series.IndependentValueBinding=.Windows.Data.Binding("EmployeeName");
  series.DependentValueBinding=.Windows.Data.Binding("Salary");
  series.Title="薪水";
  DynamicEmployeeChart.Series.Add(series);
}


  好了这里我们看下最终运行效果首先是刚启动运行时截图:

  使用Silverlight Toolkit绘制图表(上)--柱状图

  然后是 3秒的后运行截图:

使用Silverlight Toolkit绘制图表(上)--柱状图

  到这里还不算完该Control控件还支持数据分组显示比如说如果我们数据中有类型字段信息

  该Control控件是以为单位(长度就是图表列信息)这个有些难以理解下面就以个举例来加以介绍说明

  首先我们要创建个具有类型字段数据源如下:

[OperationContract]
publicList<EmployeeInfo>GetMultiSeriesEmployeeList
{
  List<EmployeeInfo>employeeList=List<EmployeeInfo>;
  employeeList.Add(EmployeeInfo{EmployeeID=1,EmployeeName="张 3",Salary=1000,Cost={100,160}});
  employeeList.Add(EmployeeInfo{EmployeeID=2,EmployeeName="李 4",Salary=1500,Cost={260,200}});
  employeeList.Add(EmployeeInfo{EmployeeID=3,EmployeeName="王 5",Salary=2000,Cost={360,330}});
  employeeList.Add(EmployeeInfo{EmployeeID=4,EmployeeName="赵 6",Salary=800,Cost={160,430}});
  employeeList.Add(EmployeeInfo{EmployeeID=5,EmployeeName="尤 7",Salary=2100,Cost={560,530}});
  employeeList.Add(EmployeeInfo{EmployeeID=6,EmployeeName="马 8",Salary=2300,Cost={660,600}});
  employeeList;
}


  大家看到了在该数据源中Cost属性即是数据类型字段该字段记录了雇员交费信息:第项为

  “住房公积金”第 2项为“个人养老金”

  下面我们就来看下该如何绑定这类数据源信息

  首先在XAML中创建该图表Control控件如下:

<charting:ChartTitle="MultiSeries"x:Name="MultiSeries"MouseLeftButtonDown="OnMouseLeftButtonDown"/>

  大家看到这里我们还绑定了鼠标单击事件该事件主要用于稍后演示图表动态效果这里先行略过:)

  接着就是我们CS代码了首先是获取数据源:

voidLoadMultiSeries
{
  dataServiceClient.GetMultiSeriesEmployeeListCompletedEventHandler<GetMultiSeriesEmployeeListCompletedEventArgs>(dataServiceClient_GetMultiSeriesEmployeeListCompleted);
  dataServiceClient.GetMultiSeriesEmployeeListAsync;
}


  然后是相应Control控件化和数据绑定代码:

voiddataServiceClient_GetMultiSeriesEmployeeListCompleted(objectsender,GetMultiSeriesEmployeeListCompletedEventArgse)
{
  ObservableCollection<EmployeeInfo>employeeList=e.Result;
 
  Action<Chart>chartModier=(chart)=>
  {
    AxisdateAxis=Axis{Orientation=AxisOrientation.Horizontal,Title="注1:住房公积金 2:个人养老金",FontStyle=FontStyles.Normal,FontSize=14f,ShowGridLines=true};
    MultiSeries.Axes.Add(dateAxis);
   
    AxisvalueAxis=Axis{Orientation=AxisOrientation.Vertical,Title="税金",Minimum=0,Maximum=800,ShowGridLines=true};
    MultiSeries.Axes.Add(valueAxis);
  };
  chartModier(MultiSeries);
  foreach(EmployeeInfoitemsSourceinemployeeList)
  {
    ColumnSeriesseries=ColumnSeries;
    series.ItemsSource=itemsSource.Cost;
    series.DependentValueBinding=null;
    series.IndependentValueBinding=null;
    series.Title=itemsSource.EmployeeName+"ID:"+itemsSource.EmployeeID;
    series.AnimationSequence=AnimationSequence.FirstToLast;
    MultiSeries.Series.Add(series);
  }    
}


  这里我们看到在Control控件数据源绑定上和前两个DEMO存在差异每个雇员交费字段本身就是个数

  组(整形)所以这里将该交费字段直接绑定到了ColumnSeriesItemsSource属性上同时将ColumnSeries

  性 DependentValueBindingIndependentValueBinding分别设置为null这里给该ColumnSeries动态显示效果

  设置成了AnimationSequence.FirstToLast下面我们会看到显示效果而相应鼠标单击事件代码摘自TOOKIT

  代码举例包这里就不多加解释了下面是相应显示效果:

使用Silverlight Toolkit绘制图表(上)--柱状图

  当我们在图表上单击鼠标时显示效果如下:

使用Silverlight Toolkit绘制图表(上)--柱状图

使用Silverlight Toolkit绘制图表(上)--柱状图

  等图表全被隐去时这时我们再单击鼠标图表会依次再显示出来

  除了数据动态加载Chart还支持数据静态绑定如下面XAML代码即是并绑定个已存在数据源:

<charting:Chart Title="Xaml绑定" x:Name="FunctionSeriesSample" MouseLeftButtonDown="OnMouseLeftButtonDown">
  <charting:Chart.Series>
    <charting:ColumnSeries
      Title="人口" AnimationSequence="FirstToLast"
      ItemsSource="{Binding PugetSound, Source={StaticResource City}}"
      IndependentValueBinding="{Binding Name}"
      DependentValueBinding="{Binding Population}"/> 
  </charting:Chart.Series>
  <charting:Chart.Axes>
    <charting:Axis AxisType="Category" Title="城市" Orientation="Horizontal" FontStyle="Italic"/>
    <charting:Axis AxisType="Linear" Title="人口" Orientation="Vertical" Minimum="0" Maximum="600000" Interval="100000" ShowGridLines="True" FontStyle="Italic"/>
  </charting:Chart.Axes>
</charting:Chart>  


  而数据源是在中直接写死如下:

/**//// <summary>
/// City business object used for charting samples.
/// </summary>
public City
{
  /**//// <summary>
  /// Gets or s the name of the city.
  /// </summary>
  public ID { get; ; }
  
  /**//// <summary>
  /// Gets or s the name of the city.
  /// </summary>
  public Name { get; ; }
  
  /**//// <summary>
  /// Gets or s the population of the city.
  /// </summary>
  public Population { get; ; }
  
  /**//// <summary>
  /// Initializes a instance of the City .
  /// </summary>
  public City
  {
  }
  
  /**//// <summary>
  /// Returns a that represents the current object.
  /// </summary>
  /// <s>A that represents the current object.</s>
  public override
  {
     Name;
  }
  
  /**//// <summary>
  /// Gets a collection of cities in the Puget Sound area.
  /// </summary>
  public ObjectCollection PugetSound
  {
    get
    {
      ObjectCollection pugetSound = ObjectCollection;
      pugetSound.Add( City { Name = "张庄", Population = 312344, ID = 1 });
      pugetSound.Add( City { Name = "李庄", Population = 411212, ID = 2 });
      pugetSound.Add( City { Name = "赵庄", Population = 261391, ID = 3 });
      pugetSound.Add( City { Name = "马家河子", Population = 530022, ID = 4 });
       pugetSound;
    }
  }
} 


  到这里有关柱状图主要功能介绍差不多了但如果开发过相应图表功能朋友会发现的前

  DEMO显示都是垂直柱状图但很多网站WebSite上显示都是水平方向柱状图比如说投票功能等其实

  Chart实现这个功能非常简要只要在我们原有CS代码基础上做很少改动即可实现这里以上面

  个DEMO为例下如何进行改造:

  下面是其dataServiceClient_GetEmployeeListCompleted思路方法改造后代码:

voiddataServiceClient_GetEmployeeListCompleted(objectsender,GetEmployeeListCompletedEventArgse)
{
  ObservableCollection<EmployeeInfo>employeeList=e.Result;
  Action<Chart>chartModier=(chart)=>
  {
    AxisdateAxis=Axis{Orientation=AxisOrientation.Vertical,Title="雇员名称",FontStyle=FontStyles.Normal,FontSize=12f,ShowGridLines=true};
    EmployeeChart.Axes.Add(dateAxis);
    AxisvalueAxis=Axis{Orientation=AxisOrientation.Horizontal,Title="薪水",Minimum=-1000,Maximum=3000,ShowGridLines=true};
    EmployeeChart.Axes.Add(valueAxis);
  };
  chartModier(EmployeeChart);
  BarSeriesseries=BarSeries;
  series.ItemsSource=employeeList;
  series.IndependentValueBinding=.Windows.Data.Binding("EmployeeName");
  series.DependentValueBinding=.Windows.Data.Binding("Salary");
  EmployeeChart.Series.Add(series);
}




  在这里我们看到了的前所设置X,Y轴在AxisOrientation属性上被做了交换设置而接着ColumnSeries对象

  也被替换成了BarSeries这样我们就完成了相应改造(更多信息参见DEMO源码BarSample)

  其它DEMO只要参照下上面所说替换方式替换下即可最终我们看个显示效果如下图所示:

使用Silverlight Toolkit绘制图表(上)--柱状图

  好了今天内容就先到这里了

  原文链接:http://www.cnblogs.com/daizhj/archive/2009/01/15/1376181.html



Tags:  silverlight是什么 silverlight.2.0 silverlight silverlight图表

延伸阅读

最新评论

发表评论