我使用livechart来创建饼图,但是每当我运行程序时,都看不到图表(https://i.stack.imgur.com/dt9io.jpg(,但是编辑代码时我可以看到图表。(https://i.stack.imgur.com/4ukv0.jpg(
这是我的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;
}
这是在窗口还是usercontrol中?
如果是窗口,请将绑定更改为:
<lvc:PieChart
Series="{Binding seriesCollection, RelativeSource={RelativeSource AncestorType=Window}}"
如果是usercontrol,您知道这要去哪里:
<lvc:PieChart
Series="{Binding seriesCollection, RelativeSource={RelativeSource AncestorType=UserControl}}"
DataContext = this;
是一个坏习惯。开始使用USERCORTROL进行此操作,并破坏了事情。即使在窗口中,它也会引起不必要的混乱。