Use Livechart to write a simple bar chart in WPF

First, you need to install the LiveCharts NuGet package in your WPF project. You can install it by searching for "LiveCharts.Wpf" through the NuGet package manager.

Then, add a CartesianChart control in the XAML file:

<Window x:Class="WpfApp12.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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:lvc="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
        xmlns:local="clr-namespace:WpfApp12"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Grid>
        <lvc:CartesianChart Series="{Binding SeriesCollection}" LegendLocation="Right"/>
    </Grid>
</Window>

Next, create a SeriesCollection property in your ViewModel class and initialize it in the constructor:

using LiveCharts;
using LiveCharts.Wpf;

public class MainViewModel
{
    public SeriesCollection SeriesCollection { get; set; }

    public MainViewModel()
    {
        SeriesCollection = new SeriesCollection
        {
            new ColumnSeries
            {
                Title = "Series 1",
                Values = new ChartValues<double> { 3, 5, 2, 7 }
            }
            ,
            new ColumnSeries
            {
                Title = "Series 2",
                Values = new ChartValues<double> { 1, 6, 4, 9 }
            }
        };
    }
}

Here we create a SeriesCollection containing a ColumnSeries. ColumnSeries represents a histogram, the Title attribute is the title of this series, and the Values ​​attribute is the data of this series.

Finally, set the ViewModel to the DataContext in MainWindow's constructor:

public MainWindow()
{
    InitializeComponent();
    DataContext = new MainViewModel();
}

Now you should be able to run this program and see a simple histogram:

 

Guess you like

Origin blog.csdn.net/u013543846/article/details/130885569