使用Silverlight 4工具包图表控件,我试图在运行时创建一个100%的图表,而在XAML中没有任何证据。为此,我在页面加载时创建空白图表:
Chart TrendChart = new Chart();
TrendChart.Name = "TrendChart";
TrendChart.Title = "Call History";
TrendChart.HorizontalContentAlignment = System.Windows.HorizontalAlignment.Stretch;
TrendChart.HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch;
TrendChart.VerticalAlignment = System.Windows.VerticalAlignment.Stretch;
TrendChart.VerticalContentAlignment = System.Windows.VerticalAlignment.Stretch;
GridPanel.Children.Add(TrendChart);
用户单击按钮以检索数据后,将创建此自定义类的列表:
private class PhoneTrendDataPoint
{
public string XValue { get; set; }
public double YValue { get; set; }
}
我使用名为CurrentCallTrends的List作为我的图表的ItemsSource。
// Update the chart with the received data
Chart TrendChart = (Chart)this.FindName("TrendChart");
// Wipe out previous chart data
TrendChart.Series.Clear();
// set the data
ColumnSeries columnSeries = new ColumnSeries();
columnSeries.Name = "Current Call Volume";
columnSeries.ItemsSource = CurrentCallTrends;
//columnSeries.SetBinding(ColumnSeries.ItemsSourceProperty, new Binding("CurrentCallTrends"));
columnSeries.DependentValueBinding = new Binding("XValue");
columnSeries.IndependentValueBinding = new Binding("YValue");
TrendChart.Series.Add(columnSeries);
问题是我遇到运行时错误,它提示我打开一个关于未设置为对象实例的对象引用的调试器。如果我将该行注释为.SetBinding,则ItemsSource将消失并且不会显示任何数据,但至少没有运行时错误。
我错过了什么?
答案 0 :(得分:0)
在进行了额外的谷歌搜索之后,我做了一些似乎有效的修改但是没有让我觉得这是最好的方法。现在显示数据,但除非没有更好的方法,否则我不接受这个答案:
// Update the chart with the received data
Chart TrendChart = (Chart)this.FindName("TrendChart");
// Wipe out previous chart data
TrendChart.Series.Clear();
// test data
KeyValuePair<string, double>[] CurrentCallData = new KeyValuePair<string, double>[CurrentCallTrends.Count];
for (int i = 0; i < CurrentCallTrends.Count; i++)
{
CurrentCallData[i] = new KeyValuePair<string, double>(CurrentCallTrends[i].XValue, CurrentCallTrends[i].YValue);
}
// set the data
ColumnSeries columnSeries = new ColumnSeries();
columnSeries.Name = "CurrentCallVolume";
columnSeries.Title = "Current Call Volume";
columnSeries.SetBinding(ColumnSeries.ItemsSourceProperty, new Binding());
//columnSeries.ItemsSource = CurrentCallTrends;
columnSeries.ItemsSource = CurrentCallData;
columnSeries.DependentValueBinding = new Binding("Value");
columnSeries.IndependentValueBinding = new Binding("Key");
TrendChart.Series.Add(columnSeries);
//this.DataContext = CurrentCallTrends;