Charting on WPF form under .NET Framework 4

    There are many libraries for plotting under .NET . The choice in favor of a solution from Microsoft impressed by the fact that it is built into the .NET Framework 4 and therefore does not require third-party libraries. Although there is one drawback - you can work with it only on the Windows Forms form, for WPF forms of full-time work with the component are not provided. Because of this, all manuals beginning with the words “drag the Chart component onto the form” walked through the forest absolutely did not help to solve the problem.


    First, it was necessary to decide how to use the Windows Forms components on a WPF form. To do this, judging by the instructions with MSDN, you need to add a link to WindowsFormsIntegration and System.Windows.Forms. You also need to add their namespaces to the element. Xaml form document and element , which will subsequently host the required component of Windows Forms:



    Now everything is ready to use Windows Forms components, but all the work of implementing the component on the form will have to be done manually. Connect to the System.Windows.Forms.DataVisualization.Charting project , add the namespace to the XAML document and the component itself to the form.



    There is a wonderful project from Microsoft , containing a lot of examples of working with the Chart component for Windows Forms. But you won’t be able to start it right away, since the environment for generating the component for Windows Forms code is generated in the InitializeComponent () method itself based on the component’s settings made by the developer. I did not find a way to call the component configurator for the WPF form, so before using the code from the examples, you will need to manually add a couple of lines of code.

    using System.Windows.Forms.DataVisualization.Charting;
    ...
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
    // Все графики находятся в пределах области построения ChartArea, создадим ее
    chart.ChartAreas.Add(new ChartArea("Default"));
    // Добавим линию, и назначим ее в ранее созданную область "Default"
    chart.Series.Add(new Series("Series1"));
    chart.Series["Series1"].ChartArea = "Default";
    chart.Series["Series1"].ChartType = SeriesChartType.Line;
    // добавим данные линии
    string[] axisXData = new string[] {"a", "b", "c"};
    double[] axisYData = new double[] {0.1, 1.5, 1.9};
    chart.Series["Series1"].Points.DataBindXY(axisXData, axisYData);
    }
    


    As a result, we get a wonderful schedule, and most importantly no third-party libraries:

    image

    Also popular now: