XML作为数据源是十分常见的使用场景,尤其是在数据可视化领域,本篇文章将阐述如何绑定ComponentOne Chart for Silverlight 到 XML 数据源。

我们通过一个示例来展示具体操作方法

首先我们需要创建一个XML数据源用于数据绑定,XML中展示了公司预算表。命名文件为 “MonthlyExpense.xml” ,添加文件到工程,设置该文件的 BuildAction 为“Resource”。

<?xml version="1.0" encoding="utf-8" ?>
<expenselists>
  <expenselist Month="January" EmployeeSalary="18000" MarketingBudget="4000" RecruitmentBudget="9000"/>
  <expenselist Month="February" EmployeeSalary="15000" MarketingBudget="2500" RecruitmentBudget="10000" />
  <expenselist Month="March" EmployeeSalary="30500" MarketingBudget="1000" RecruitmentBudget="2000"/>
</expenselists>

 

由于 Silverlight 平台的限制,需要把 XML 文件加载到 XMLDocument 流文件中,以下是代码:

var resource = Application.GetResourceStream(new Uri("/" + new AssemblyName(Assembly.GetExecutingAssembly().FullName).Name + ";component/MonthlyExpense.xml", UriKind.Relative));
XDocument myXML = XDocument.Load(resource.Stream);

 

现在“myXML” 对象包含了“MonthlyExpense.xml” 文件中的数据。 接下来创建一个结构类似于 XML 文件的类。代码如下:

public class ExpenseList
{
    public string Month { get; set; }
    public int EmployeeSalary { get; set; }
    public int MarketingBudget { get; set; }
    public int RecruitmentBudget { get; set; }
}

 

创建 ExpenseList 类列表,使用以下代码填充数据:

List<ExpenseList> expenselist =
(from list in myXML.Descendants("expenselist")
    select new ExpenseList()
    {
          Month = list.Attribute("Month").Value,
          EmployeeSalary = int.Parse(list.Attribute("EmployeeSalary").Value),
          MarketingBudget = int.Parse(list.Attribute("MarketingBudget").Value),
          RecruitmentBudget = int.Parse(list.Attribute("RecruitmentBudget").Value),
  
}).ToList();

 

设置数据源给 ComponentOne Chart for Silverlight:-

c1Chart1.Data.ItemsSource = countrylist;

 

设置 ItemSource属性之后,需要在XAML页面绑定 DataSeries 到 ComponentOne chart:

       <c1:C1Chart c1:C1NagScreen.Nag="True" ChartType="Column" Margin="0,4,12,12" Name="c1Chart1" Palette="Office" Grid.Row="1">
        <c1:C1Chart.Data >
            <c1:ChartData ItemNameBinding="{Binding Month}">
                <c1:DataSeries  Label="Employee Salary" ValueBinding="{Binding EmployeeSalary}" c1:C1NagScreen.Nag="True" />
                <c1:DataSeries  Label="Marketing Budget" ValueBinding="{Binding MarketingBudget}" c1:C1NagScreen.Nag="True" />
                <c1:DataSeries  Label="Recrutiment Budget" ValueBinding="{Binding RecruitmentBudget}" c1:C1NagScreen.Nag="True" />
            </c1:ChartData>
        </c1:C1Chart.Data>
        <c1:C1ChartLegend c1:C1NagScreen.Nag="True"></c1:C1ChartLegend>
       </c1:C1Chart >

 

运行 Demo 效果图如下:

MonthlyExpenses

 

Demo 下载:

VS2010 + Silverlight 5.0 + C#