WinForm程序中使用Echarts图表

发布时间 2023-11-01 11:54:44作者: 我本梁人

WinForm程序中使用Echarts

实现原理: WebBrowser + HTML

第一步:在窗体中添加WebBrowser控件

1.在工具箱中找到WebBrowser控件,拖动到窗体中


  1. 设置WebBrowser控件的属性
    ScriptErrorsSuppressed:true;//设置是否允许脚本错误
    IsWebBrowserContextMenuEnabled:false; //禁用浏览器菜单

第二步:在项目中引入Echarts.js文件

特别注意:引用Echarts.js版本不得高于3.8.5,否则WebBrowser无法加载

第三步:在项目中新建一个index.html文件,并添加Echarts.js文件

此时我们实现的效果是点击窗体上加载的按钮就能重新加载Echarts图表。
效果图如下:


Js部分添加WinForm窗体按钮的点击所调用的事件

 //通过eval 函数传递出json数据
       //updateValue为WinForm后台传递数据所调用的方法
        function updateValue(value) {
            function customJSONParse(jsonString) {
                return eval('(' + jsonString + ')');
            }

WinForm部分添加按钮的点击事件

     /// 加载数据
     /// </summary>
     /// <param name="sender"></param>
     /// <param name="e"></param>
     private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
     {
         Object[] jsonobjec = dataItems.ToArray(); 

         // 构建JavaScript代码,调用HTML页面中的JavaScript函数,并传递参数
         string script = "updateValue('" + JsonConvert.SerializeObject(jsonobjec) + "');"; // 假设HTML中有名为updateValue的JavaScript函数
         // 执行JavaScript代码
         wb1.Document.InvokeScript("eval", new object[] { script });

     }

WinForm设置Webbrowser的属性

 private void Form2_Load(object sender, EventArgs e)
     {

         wb1.ObjectForScripting = this; 
          //Url:设置访问的html的地址
         wb1.Url = new Uri(Application.StartupPath.Replace("\\bin\\Debug", "") + "\\index.html");
   }

HTML代码

        <!DOCTYPE html>

        <html lang="en" xmlns="http://www.w3.org/1999/xhtml">
        <head>
            <meta charset="utf-8" />
            <title></title>
            <script src="ECharts.JS/echarts.js"></script>
            <!--<script src="https://cdnjs.cloudflare.com/ajax/libs/echarts/3.8.5/echarts.js"></script>-->
        </head>
        <body>
            <div id="main" style="width:1500px;height:600px;"></div>
            <script type="text/javascript">
                function updateValue(value) {
                    //alert("Value received from C#: " + value);
                    // 解析JSON字符串为JavaScript数组
                    //var arr = JSON.parse(value);
                    function customJSONParse(jsonString) {
                        return eval('(' + jsonString + ')');
                    }

                    //var jsonString = '{"name": "John", "age": 30}';
                    var parsedObject = customJSONParse(value);

                    var listPrice92 = new Array();
                    var listPrice95 = new Array();
                    var listPriceV0 = new Array();

                    var listDate = new Array();
                    // 输出数组内容
                    for (var i = 0; i < parsedObject.length; i++) {
                        listDate[i] = parsedObject[i].DIM_DATE.toString().substring(0, 10);
                        listPrice92[i] = parsedObject[i].V92;
                        listPrice95[i] = parsedObject[i].V95;
                        listPriceV0[i] = parsedObject[i].V0;
                    }

                    // 基于准备好的dom,初始化echarts实例
                    var myChart = echarts.init(document.getElementById('main'));
                    // 指定图表的配置项和数据
                    var option = {
                        title: {
                            text: '油价曲线'
                        },
                        tooltip: {
                            trigger: 'axis'
                        },
                        legend: {
                            data: ['92', '95', 'V0']
                        },
                        grid: {
                            left: '3%',
                            right: '4%',
                            bottom: '3%',
                            containLabel: true
                        },
                        toolbox: {
                            feature: {
                                saveAsImage: {}
                            }
                        },
                        xAxis: {
                            type: 'category',
                            boundaryGap: false,
                            data: listDate.sort()
                        },
                        yAxis: {
                            scale: true
                            //type: 'value'
                        },
                        series: [
                            {
                                name: '92',
                                type: 'line',
                                data: listPrice92,
                                itemStyle: { normal: { label: { show: true } } },
                                lineStyle: { normal: { color: "#FF2e63", width: 3 } }
                            },
                            {
                                name: '95',
                                type: 'line',
                                data: listPrice95,
                                itemStyle: { normal: { label: { show: true } } },
                                lineStyle: { normal: { color: "#252a34", width: 3 } }
                            },
                            {
                                name: 'V0',
                                type: 'line',
                                data: listPriceV0,
                                itemStyle: { normal: { label: { show: true } } },
                                lineStyle: { normal: { color: "#08d9d6", width: 3 } }
                            }
                        ]
                    };


                    //  使用刚指定的配置项和数据显示图表。
                    myChart.setOption(option);
                }
            </script>
        </body>
        </html>

WinForm代码


using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace XXXXX
{
  //设置Com对外可访问
  [System.Runtime.InteropServices.ComVisible(true)]
  public partial class Form2 : Form
  {
      public Form2(List<DataItem> data)
      {
          InitializeComponent();

          dataItems = data;
      }

      public List<DataItem> dataItems;
      
      private void Form2_Load(object sender, EventArgs e)
      {

          wb1.ObjectForScripting = this;
          wb1.Url = new Uri(Application.StartupPath.Replace("\\bin\\Debug", "") + "\\index.html");
      }

      private void btnLoad_Click(object sender, EventArgs e)
      {
           
          wb1.Url = new Uri(Application.StartupPath.Replace("\\bin\\Debug","") + "\\index.html");
      }
      /// <summary>
      /// 加载数据
      /// </summary>
      /// <param name="sender"></param>
      /// <param name="e"></param>
      private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
      {
             Object[] jsonobjec = dataItems.ToArray();
          //    wb1.Document.InvokeScript("getdata", jsonobjec);

          // 准备要传递的值
          string valueToPass = "Hello from C#!";

          // 构建JavaScript代码,调用HTML页面中的JavaScript函数,并传递参数
          string script = "updateValue('" + JsonConvert.SerializeObject(jsonobjec) + "');"; // 假设HTML中有名为updateValue的JavaScript函数

          // 执行JavaScript代码
          wb1.Document.InvokeScript("eval", new object[] { script });

      } 
  } 
}