WPF下實現堆積柱狀圖
阿新 • • 發佈:2019-02-17
VS2010下
準備依賴檔案:
System.Windows.Forms.dll;
System.Windows.Forms.DataVisualization.Charting.dll;
WindowsFormIntegration.dll
MainWindow.xaml編輯如下
<Window x:Class="MainWindow.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:WinFormHost="clr-namespace:System.Windows.Forms.Integration;assembly=WindowsFormsIntegration" xmlns:WinFormControls="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms" xmlns:wfc="clr-namespace:System.Windows.Forms.DataVisualization.Charting;assembly=System.Windows.Forms.DataVisualization" Title="WPF Chart Demo" Width="903" Height="581"> <Grid Name="grid1"> <WindowsFormsHost Margin="0,47,0,0"> <wfc:Chart Name="Chart1"/> </WindowsFormsHost> </Grid> </Window>
MainWindow.xaml.cs程式碼如下
private void button1_Click(object sender, RoutedEventArgs e) { addData(); } private void addData() { var windowsFormsHost = (WindowsFormsHost)grid1.Children[0]; var chart = (Chart)windowsFormsHost.Child; chart.Series.Clear(); chart.ChartAreas.Clear(); // ChartArea追加 chart.ChartAreas.Add("ChartArea1"); chart.ChartAreas[0].AxisX.Interval = 1; chart.ChartAreas[0].Axes[0].MajorGrid.Enabled = false; chart.ChartAreas[0].BorderColor =System.Drawing.Color.Red; //series的製作和值的追加 Series seriesSin = new Series(); seriesSin.ChartType = SeriesChartType.StackedColumn; seriesSin.MarkerStyle = MarkerStyle.Circle; Series seriesCos = new Series(); seriesCos.ChartType = SeriesChartType.StackedColumn; seriesCos.MarkerStyle = MarkerStyle.Circle; string[] xValues = new string[] { "A", "B", "C", "D", "E"}; //x軸的資料 int[,] yValues = new int[,] { { 10, 20, 30, 40, 50 }, { 20, 40, 60, 80, 100 } }; //y軸的資料 for (int x = 1; x <= xValues.Length; x++) { seriesCos.IsValueShownAsLabel = true; seriesSin.IsValueShownAsLabel = true; seriesSin.Points.AddXY(x, x); seriesCos.Points.AddXY(x, x); } chart.Series.Add(seriesSin); chart.Series.Add(seriesCos); }
效果:
上述的
seriesSin.ChartType = SeriesChartType.StackedColumn;
可以設定各種的統計圖表如:
更具上訴程式碼就可以實現;
專案和相關dll:下載