Michael Lee
Michael Lee

Reputation: 67

Pie chart not displayed WPF

I used livechart in order to create a Pie chart, but whenever I run the program, the chart can't be seen (https://i.sstatic.net/dT9IO.jpg), but I can see the chart when I'm editing the code. (https://i.sstatic.net/4ukv0.jpg)

This is my WPF code:

        <lvc:PieChart Series="{Binding seriesCollection}" Height="150" InnerRadius="100" LegendLocation="Bottom" DataClick="Chart_OnDataClick" Hoverable="True">
            <lvc:PieChart.ChartLegend>
                <lvc:DefaultLegend BulletSize="20"></lvc:DefaultLegend>
            </lvc:PieChart.ChartLegend>
            <lvc:PieChart.DataTooltip>
                <lvc:DefaultTooltip BulletSize="20"></lvc:DefaultTooltip>
            </lvc:PieChart.DataTooltip>
        </lvc:PieChart>

And this is my c# code:

public Overview()
{
    InitializeComponent();
    NorthwindEntities db = new NorthwindEntities();
    var data = (from d in db.Sales_by_Categories group d by d.CategoryName into grouped select new { Key = grouped.Key, Sum = grouped.Sum(e => (double)e.ProductSales) });
    IEnumerable<Categorysales> datas = from c in data.AsEnumerable() select new Categorysales(c.Key, c.Sum);


    seriesCollection = new SeriesCollection();
    foreach (var item in datas)
    {
        seriesCollection.Add(new PieSeries { Title = item.Categoryname, Values = new ChartValues<ObservableValue> { new ObservableValue(item.Categorysum) }, DataLabels = true});//, LabelPoint = PointLabel 
    }
   /* PointLabel = chartPoint =>
        string.Format("{0} ({1:P})", chartPoint.Y, chartPoint.Participation);*/

   // DataContext = this;
}
public SeriesCollection seriesCollection { get; set; }



public Func<ChartPoint, string> PointLabel { get; set; }

private void Chart_OnDataClick(object sender, ChartPoint chartpoint)
{
    var chart = (LiveCharts.Wpf.PieChart)chartpoint.ChartView;

    //clear selected slice.
    foreach (PieSeries series in chart.Series)
        series.PushOut = 0;

    var selectedSeries = (PieSeries)chartpoint.SeriesView;
    selectedSeries.PushOut = 8;
}

Upvotes: 2

Views: 1388

Answers (1)

Is this in a Window or a UserControl?

If it's a window, change the binding to this:

<lvc:PieChart 
    Series="{Binding seriesCollection, RelativeSource={RelativeSource AncestorType=Window}}"

If it's a UserControl, you know where this is going:

<lvc:PieChart 
    Series="{Binding seriesCollection, RelativeSource={RelativeSource AncestorType=UserControl}}"

DataContext = this; is a bad habit. Start doing that with UserControls and it breaks things. Even in a Window, it creates needless confusion.

Upvotes: 4

Related Questions