我使用livechart来创建饼图,但每当我运行程序时,都无法看到图表(http://imgur.com/GWecwgD),但我在编辑代码时可以看到图表。 (http://imgur.com/zVvkK3v)
这是我的WPF代码:
<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>
这是我的c#代码:
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;
}
答案 0 :(得分:3)
这是在Window还是UserControl中?
如果是窗口,请将绑定更改为:
<lvc:PieChart
Series="{Binding seriesCollection, RelativeSource={RelativeSource AncestorType=Window}}"
如果是UserControl,你知道这是怎么回事:
<lvc:PieChart
Series="{Binding seriesCollection, RelativeSource={RelativeSource AncestorType=UserControl}}"
DataContext = this;
是一个坏习惯。用UserControls开始这样做,它打破了事情。即使在窗口中,它也会造成不必要的混乱。