Search code examples
c#wpflivecharts

Use PieChart with LiveCharts and WPF .NET Core


I use chart plugin for WPF: https://lvcharts.net

In xaml I have:

<Window x:Class="GoogleDriveManager.WPF.ChartWindow"
        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:local="clr-namespace:GoogleDriveManager.WPF" xmlns:wpf="clr-namespace:LiveCharts.Wpf;assembly=LiveCharts.Wpf"
        mc:Ignorable="d"
        Title="Chart statistics" Height="450" Width="800">
    <Grid>
        <wpf:PieChart LegendLocation="Bottom" Series="{Binding Items}"/>
  </Grid>
</Window>

and code behind:

public ChartWindow()
{
  InitializeComponent();
  DataContext = this;

  Items = new SeriesCollection();

  ContentRendered += (s, ev) =>
  {
    Dictionary<string, List<string>> data = GetData(...);
    foreach (var item in data)
    {
      ISeriesView series = new PieSeries(new { title = item.Key });
      IChartValues values = new ChartValues<string>(item.Value);
      series.Values = values;
      Items.Add(series);
    }
  };
}

public SeriesCollection Items { get; }

But seems that the window is empty.


Solution

    1. You should transfer string values to double
    2. Use PieSeries properties Title to assign title

    I create a simple case and this code works:

    ContentRendered += (s, ev) =>
    {
        Dictionary<string, List<string>> data = new Dictionary<string, List<string>>(){
            {"AAA", new List<string>(){"1","2"}},
            {"BBB", new List<string>(){"3","4"}}
        };
        foreach (var item in data)
        {
            var curValues = item.Value.Select(x => double.Parse(x)).ToList();
            ISeriesView series = new PieSeries{
                Title = item.Key,
                Values = new ChartValues<double>(curValues),
                DataLabels = true
            };
            Items.Add(series);
        }
    };