Programmatically create a ColumnSeries WPF Toolkit Charts

半腔热情 提交于 2019-12-06 14:18:11

问题


I am trying to programmatically add a column series to a wpf toolkit chart. My xaml is an empty chart. The code results in an unhandled exception, Object reference not set to an instance of an object. Any clues to why this does not work?

<charting:Chart Name="MyChart">

my code behind is

List<KeyValuePair<int,int>> testList = new List<KeyValuePair<int,int>>();

testList.Add(new KeyValuePair<int,int> (1,2));

testList.Add(new KeyValuePair<int,int> (2,3)); 

ColumnSeries mySeries = new ColumnSeries();

mySeries.Title = "TEST";


mySeries.IndependentValueBinding = new Binding("key");

mySeries.DependentValueBinding = new Binding("value");

mySeries.ItemsSource = testList;

MyChart.Series.Add(mySeries);

回答1:


You should use "Key" instead of "key" and "Value" instead of "value" in the binding.




回答2:


I have come to this problem too, after i have upgraded my application from .NET FRAMEWORK 3.5 to 4.0, suddently the chart class stopped working. When i called Show() method on form that had the chart with dynamic columnseries, instead of displaying the new window, this error popped up: Object reference not set to an instance of an object. If i remove the itemsource link to Dictionary, or change the dynamic columnseries to static XAML version, it works though, but this static version is unusable for most users.

anybody has idea how to implement this directly in WPF .NET Framework 4.0? or its bug in wpftoolkit which is targetted to .NET 3.5 ?

public void SetChartData(IDictionary<string, IDictionary<string, double>> prod, String title, String labelAxis)
        {   
           chart.Title = title;
           LinearAxis ca = new LinearAxis();
           ca.Orientation = AxisOrientation.Y;
           ca.Minimum = 0;
           chart.Axes.Add(ca);
           foreach (KeyValuePair<string, IDictionary<string, double>> kvp in prod)
           {
               ColumnSeries cser = new ColumnSeries();
               cser.Title = kvp.Key;
             cser.DependentValueBinding = new Binding("Value");
              cser.IndependentValueBinding = new Binding("Key");
              cser.ItemsSource = kvp.Value;
               chart.Series.Add(cser);
           }
        }

i have found one possible workaround:

  • create new WPF project library for ex. MyChart, create a class that will return WPF Window with chart inside.
  • setup and compile the chart library project as .NET Framework 3.5 (client)
  • calling MyChartClass.Show(); inside main program .NET Framework 4.0 will display the chart properly


来源:https://stackoverflow.com/questions/3926036/programmatically-create-a-columnseries-wpf-toolkit-charts

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!