LiveCharts 折线图,柱状图,饼状图基本绑定实现(WPF)

Stella981
• 阅读 2387

总体效果如图:

LiveCharts 折线图,柱状图,饼状图基本绑定实现(WPF)

1.折线图的简单绑定

此处对折线图的横坐标坐标与时间进行绑定

 LiveCharts 折线图,柱状图,饼状图基本绑定实现(WPF)

前台代码:

<lvc:CartesianChart Series="{Binding LineSeriesCollection}"
                            LegendLocation="Right">
            <lvc:CartesianChart.AxisY>
                <lvc:Axis></lvc:Axis>
            </lvc:CartesianChart.AxisY>
            <lvc:CartesianChart.AxisX>
                <lvc:Axis Labels="{Binding LineXLabels}"></lvc:Axis>
            </lvc:CartesianChart.AxisX>
</lvc:CartesianChart>

后台代码:

void GetLineSeriesData()
{
      List<string> titles = new List<string> { "苹果", "香蕉", "梨" };
      List<List<double>> values = new List<List<double>>
      {
           new List<double> { 30, 40, 60 },
           new List<double> { 20, 10, 50 },
           new List<double> { 10, 50, 30 }
       };
       List<string> _dates = new List<string>();
       //获取当前月的日期
       _dates = GetCurrentMonthDates();
       for (int i = 0; i < titles.Count; i++)
       {
         LineSeries lineseries = new LineSeries();
         lineseries.DataLabels = true;
         lineseries.Title = titles[i];
         lineseries.Values = new ChartValues<double>(values[i]);
         LineXLabels.Add(_dates[i]);
         LineSeriesCollection.Add(lineseries);
       }
}

2.柱状图的简单绑定

LiveCharts 折线图,柱状图,饼状图基本绑定实现(WPF)

前台代码:

<lvc:CartesianChart Series="{Binding ColunmSeriesCollection}"
                            LegendLocation="Right">
            <lvc:CartesianChart.AxisX>
                <lvc:Axis Labels="{Binding ColumnXLabels}"></lvc:Axis>
            </lvc:CartesianChart.AxisX>
            <lvc:CartesianChart.AxisY>
                <lvc:Axis></lvc:Axis>
            </lvc:CartesianChart.AxisY>
</lvc:CartesianChart>

后台代码:

 void GetColunmSeriesData()
{
      List<string> titles = new List<string> { "Edge", "Chrome", "Firefox", "Other" };
      List<double> columnValues = new List<double> { 10, 70, 15, 5 };

      for (int i = 0; i < titles.Count; i++)
      {
          ColumnXLabels[i] = titles[i];
      }
      ColumnSeries colunmseries = new ColumnSeries();
      colunmseries.DataLabels = true;
      colunmseries.Title = "浏览器份额";
      colunmseries.Values = new ChartValues<double>(columnValues);
      ColunmSeriesCollection.Add(colunmseries);

}

3.饼状图的简单绑定

LiveCharts 折线图,柱状图,饼状图基本绑定实现(WPF)

前台代码:

<lvc:PieChart LegendLocation="
                    Bottom"
                      Series="{Binding PieSeriesCollection}"
                      DataClick="Chart_OnDataClick"
                      Hoverable="False">
            <lvc:PieChart.DataTooltip>
                <lvc:DefaultTooltip BulletSize="10"></lvc:DefaultTooltip>
            </lvc:PieChart.DataTooltip>
</lvc:PieChart>

后台代码:

void GetPieSeriesData()
{
         List<string> titles = new List<string> { "C#", "Java", "Python" };
         List<double> pieValues = new List<double> { 60, 30, 10 };
         ChartValues<double> chartvalue = new ChartValues<double>();
         for (int i = 0; i < titles.Count; i++)
         {
                chartvalue = new ChartValues<double>();
                chartvalue.Add(pieValues[i]);
                PieSeries series = new PieSeries();
                series.DataLabels = true;
                series.Title = titles[i];
                series.Values = chartvalue;
                PieSeriesCollection.Add(series);
         }
}

4.整体代码

项目结构:

LiveCharts 折线图,柱状图,饼状图基本绑定实现(WPF)

前台代码:

<Window x:Class="LiveChartBindingDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:LiveChartBindingDemo"
        mc:Ignorable="d"
        Title="MainWindow"
        Height="720"
        Width="1280">
    <UniformGrid>
        <lvc:CartesianChart Series="{Binding LineSeriesCollection}"
                            LegendLocation="Right">
            <lvc:CartesianChart.AxisY>
                <lvc:Axis></lvc:Axis>
            </lvc:CartesianChart.AxisY>
            <lvc:CartesianChart.AxisX>
                <lvc:Axis Labels="{Binding LineXLabels}"></lvc:Axis>
            </lvc:CartesianChart.AxisX>
        </lvc:CartesianChart>
        <lvc:CartesianChart Series="{Binding ColunmSeriesCollection}"
                            LegendLocation="Right">
            <lvc:CartesianChart.AxisX>
                <lvc:Axis Labels="{Binding ColumnXLabels}"></lvc:Axis>
            </lvc:CartesianChart.AxisX>
            <lvc:CartesianChart.AxisY>
                <lvc:Axis></lvc:Axis>
            </lvc:CartesianChart.AxisY>
        </lvc:CartesianChart>
        <lvc:PieChart LegendLocation="
                    Bottom"
                      Series="{Binding PieSeriesCollection}"
                      DataClick="Chart_OnDataClick"
                      Hoverable="False">
            <lvc:PieChart.DataTooltip>
                <lvc:DefaultTooltip BulletSize="10"></lvc:DefaultTooltip>
            </lvc:PieChart.DataTooltip>
        </lvc:PieChart>
    </UniformGrid>
</Window>

MainWindow.xaml.cs代码:

using LiveCharts;
using LiveCharts.Wpf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace LiveChartBindingDemo
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        MainWindowViewModel mainWindowViewModel = new MainWindowViewModel(); 
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = mainWindowViewModel;
        }

        private void Chart_OnDataClick(object sender, ChartPoint chartpoint)
        {
            var chart = (LiveCharts.Wpf.PieChart)chartpoint.ChartView;

            //clear selected slice.
            foreach (PieSeries series in chart.Series)
                series.PushOut = 0;

            var selectedSeries = (PieSeries)chartpoint.SeriesView;
            selectedSeries.PushOut = 8;
        }
    }
}

MainWindowViewModel代码

using LiveCharts;
using LiveCharts.Wpf;
using System;
using System.Collections.Generic;

namespace LiveChartBindingDemo
{
    public class MainWindowViewModel
    {

        SeriesCollection lineSeriesCollection = new SeriesCollection();
        SeriesCollection colunmSeriesCollection = new SeriesCollection();
        SeriesCollection pieSeriesCollection = new SeriesCollection();
        List<string> _lineXLabels = new List<string>();
        List<string> _columnXLabels = new List<string>();

        public MainWindowViewModel()
        {
            GetLineSeriesData();
            GetColunmSeriesData();
            GetPieSeriesData();
        }

        #region 属性
        /// <summary>
        /// 折线图集合
        /// </summary>
        public SeriesCollection LineSeriesCollection
        {
            get
            {
                return lineSeriesCollection;
            }

            set
            {
                lineSeriesCollection = value;
            }
        }

        /// <summary>
        /// 柱状图集合
        /// </summary>
        public SeriesCollection ColunmSeriesCollection
        {
            get
            {
                return colunmSeriesCollection;
            }

            set
            {
                colunmSeriesCollection = value;
            }
        }
        
        /// <summary>
        /// 饼图图集合
        /// </summary>
        public SeriesCollection PieSeriesCollection
        {
            get
            {
                return pieSeriesCollection;
            }

            set
            {
                pieSeriesCollection = value;
            }
        }

        /// <summary>
        /// 折线图X坐标
        /// </summary>
        public List<string> LineXLabels
        {
            get
            {
                return _lineXLabels;
            }

            set
            {
                _lineXLabels = value;
            }
        }

        /// <summary>
        /// 柱状图X坐标
        /// </summary>
        public List<string> ColumnXLabels
        {
            get
            {
                return _columnXLabels;
            }

            set
            {
                _columnXLabels = value;
            }
        }
        #endregion

        #region 方法
        void GetLineSeriesData()
        {
            List<string> titles = new List<string> { "苹果", "香蕉", "梨" };
            List<List<double>> values = new List<List<double>>
            {
                new List<double> { 30, 40, 60 },
                new List<double> { 20, 10, 50 },
                new List<double> { 10, 50, 30 }
            };
            List<string> _dates = new List<string>();
            _dates = GetCurrentMonthDates();
            for (int i = 0; i < titles.Count; i++)
            {
                LineSeries lineseries = new LineSeries();
                lineseries.DataLabels = true;
                lineseries.Title = titles[i];
                lineseries.Values = new ChartValues<double>(values[i]);
                LineXLabels.Add(_dates[i]);
                LineSeriesCollection.Add(lineseries);
            }
        }

        void GetColunmSeriesData()
        {
            List<string> titles = new List<string> { "Edge", "Chrome", "Firefox", "Other" };
            List<double> columnValues = new List<double> { 10, 70, 15, 5 };

            for (int i = 0; i < titles.Count; i++)
            {
                ColumnXLabels.Add(titles[i]);
            }
            ColumnSeries colunmseries = new ColumnSeries();
            colunmseries.DataLabels = true;
            colunmseries.Title = "浏览器份额";
            colunmseries.Values = new ChartValues<double>(columnValues);
            ColunmSeriesCollection.Add(colunmseries);

        }

        void GetPieSeriesData()
        {
            List<string> titles = new List<string> { "C#", "Java", "Python" };
            List<double> pieValues = new List<double> { 60, 30, 10 };
            ChartValues<double> chartvalue = new ChartValues<double>();
            for (int i = 0; i < titles.Count; i++)
            {
                chartvalue = new ChartValues<double>();
                chartvalue.Add(pieValues[i]);
                PieSeries series = new PieSeries();
                series.DataLabels = true;
                series.Title = titles[i];
                series.Values = chartvalue;
                PieSeriesCollection.Add(series);
            }
        }

        void ThreeColumnData()
        {
            List<string> titles = new List<string> { "苹果", "香蕉", "梨" };
            //三列示例数据
            List<List<double>> threeColunmValues = new List<List<double>>
            {
                new List<double> { 30, 40, 60 },
                new List<double> { 20, 10, 50 },
                new List<double> { 10, 50, 30 }
            };


            for (int i = 0; i < titles.Count; i++)
            {
                ColumnSeries colunmseries = new ColumnSeries();
                colunmseries.DataLabels = true;
                colunmseries.Title = titles[i];
                colunmseries.Values = new ChartValues<double>(threeColunmValues[i]);

                ColunmSeriesCollection.Add(colunmseries);
            }
        }
        
        /// <summary>
        /// 获取当前月的每天的日期
        /// </summary>
        /// <returns>日期集合</returns>
        List<string> GetCurrentMonthDates()
        {
            List<string> dates = new List<string>();
            DateTime dt = DateTime.Now;
            int year = dt.Year;
            int mouth = dt.Month;
            int days = DateTime.DaysInMonth(year, mouth);
            //本月第一天时间      
            DateTime dt_First = dt.AddDays(1 - (dt.Day));
            dates.Add(String.Format("{0:d}", dt_First.Date));

            for (int i = 1; i < days; i++)
            {
                DateTime temp = dt_First.AddDays(i);
                dates.Add(String.Format("{0:d}", temp.Date));
            }
            return dates;
        }
        #endregion
    }
}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
待兔 待兔
5个月前
手写Java HashMap源码
HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程HashMap的使用教程22
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
11个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这