为livechart的piechart 添加数据绑定 莫忘了

livechart 里面的 所有chart分两种 一种winform用的 一种wpf用的。

winform用的是把wpf打包做的。

winform也有数据绑定机制,但是功能没有wpf强

 pieChart1.DataBindings.Add(new Binding("Series", datasource, "seriescollection"));

将一个类 datasource 下面的 seriescollection 属性绑定到 piechart1的 series 属性上去。

seriescollection就是一个SeriesCollection对象  但这样明显无法做到我绑定到一个list表 或则datatable的意愿。

所以我把winform 版的piecharts做了个一个继承 ,因为继承出来的可以访问到 里面的核心 WpfBase

 1  public class WinFormPieChartEx1 : LiveCharts.WinForms.PieChart
 2     {
 3         //这个是数据源的包装类
 4         private datasource _datasource_Container_Object;
 5         public datasource datasource_Container_Object
 6         {
 7             get
 8             {
 9                 if (_datasource_Container_Object == null)
10                     _datasource_Container_Object = new datasource();
11                 return _datasource_Container_Object;
12             }
13             set
14             {
15                 _datasource_Container_Object = value;
16             }
17         }
18 
19         public WinFormPieChartEx1():base()
20         {
21             ///数据源下的sourceList 属性是保存的数据
22             System.Windows.Data.Binding binding = new System.Windows.Data.Binding("sourceList");
23             //sourceList所在的类
24             binding.Source = datasource_Container_Object;
25             //单向绑定  datasource_Container_Object.sourceList改变 触发 piechart改变
26             binding.Mode = System.Windows.Data.BindingMode.OneWay;
27             ///转换器 很重要 实现了 list<double> 到seriesCollection的改变
28             binding.Converter = new DoubleListConvertToSeriesCollection();
29             ///将以上建立的binding关联到piechart的Seriecs对象
30             WpfBase.SetBinding(LiveCharts.Wpf.PieChart.SeriesProperty, binding);
31         }
32     }
33 
34     //转换器
35     public class DoubleListConvertToSeriesCollection : System.Windows.Data.IValueConverter
36     {
37         public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
38         {
39             List<double> _value = (List<double>)value;
40             SeriesCollection result = new SeriesCollection();
41             foreach (double n in _value)
42             {
43                 ChartValues<double> chartvalue = new ChartValues<double>();
44                 chartvalue.Add(n);
45                 PieSeries series = new PieSeries();
46                 
47                 series.Values = chartvalue;
48                 result.Add(series);
49             }
50             return result;
51         }
52 
53         public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
54         {
55             return null;
56         }
57     }

猜你喜欢

转载自www.cnblogs.com/ghostalker/p/12325781.html
今日推荐