背景:用wpf想把数据在显示在图表,以一条曲线展示的时候,发现出了问题,wpf不像winform,直接就有chart控件,所以就花了点精力,学会了怎么调用chart控件,最终是为了把数据能够以图表曲线的形式展示出来。
当然,wpf还有其他显示更美观曲线图的方法,现在还没接触到。慢慢来吧,有好的方法可以告诉我一声哦
1. 添加引用
首先在你的项目引用里添加几个新的dll文件:
System.Windows.Forms.dll
WindowsFormsIntegration.dll
System.Windows.Forms.DataVisualization.dll
如图
2. xaml文件修改
在xaml文件片首添加以下代码:
xmlns:wfi="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration"
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
xmlns:Chr="clr-namespace:System.Windows.Forms.DataVisualization.Charting;assembly=System.Windows.Forms.DataVisualization"
并在文件中间添加以下代码:
<WindowsFormsHost x:Name="WFHost_HistoryFlow" Margin="402,0,1.333,0.667" Height="239" VerticalAlignment="Bottom">
<Chr:Chart x:Name="chart"/>
</WindowsFormsHost>
该代码解释;由于wpf没有chart控件,所以以上代码就是给一个chart图表,大小都是自己设置。这里我把这个图表命名为 chart。
总体代码如图所示:
2. xaml.cs 文件修改
xaml.cs文件改成
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;
using System.Windows.Forms;
using System.Windows.Forms.DataVisualization.Charting;
using System.Data;
namespace UsingChart
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
float[] X = new float[10];
float[] Y = new float[10];
for (int i = 0; i < 10; i++) {
X[i] = i;
Y[i] = i * i;
}
ChartArea ca0 = new ChartArea("ChartArea0");
this.chart.ChartAreas.Add(ca0);
//ChartArea ca1 = new ChartArea("ChartArea1");
//this.chart.ChartAreas.Add(ca1);
this.chart.ChartAreas[0].CursorX.IsUserEnabled = true;
this.chart.ChartAreas[0].CursorX.AutoScroll = true;
this.chart.ChartAreas[0].CursorX.IsUserSelectionEnabled = true;
this.chart.ChartAreas[0].AxisX.ScaleView.Zoomable = true;
this.chart.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
this.chart.ChartAreas[0].AxisX.ScrollBar.Size = 10;
this.chart.ChartAreas[0].AxisX.ScrollBar.ButtonStyle = ScrollBarButtonStyles.All;
this.chart.ChartAreas[0].AxisX.ScaleView.SmallScrollSize = double.NaN;
this.chart.ChartAreas[0].AxisX.ScaleView.SmallScrollMinSize = 1;
this.chart.Series.Add("Series0");
this.chart.Series[0].Points.DataBindXY(X, Y);
this.chart.Series[0].ChartType = (SeriesChartType)3;
}
}
}
代码解释: 我这里自己写了一个函数 y=x^2, 其中x从0到9,所以运行后会在界面上显示这条曲线,如图所示
如果用你自己的数据,把数据改改,换个方式就可以啦,第二段代码也比较容易看懂,看不懂的可以跟我交流,或者有更好的方法的同伴。