【发布时间】:2020-09-04 02:53:38
【问题描述】:
我的代码目前有问题。
基本上我需要在我的应用程序的一个网格中显示 2 个图表,但它似乎不起作用。 问题是一张图会显示,而第二张图不会绘制。
下面是使用的代码:
XAML:
<Grid>
<lvc:CartesianChart x:Name="cartchartdb" Series="{Binding SeriesCollection}" LegendLocation="Right" Margin="10,249,578.4,218.2" >
<lvc:CartesianChart.AxisY>
<lvc:Axis Title="Average Gap (Meter)" LabelFormatter="{Binding YFormatter}"></lvc:Axis>
</lvc:CartesianChart.AxisY>
<lvc:CartesianChart.AxisX>
<lvc:Axis Title="Time" Labels="{Binding Labels}"></lvc:Axis>
</lvc:CartesianChart.AxisX>
</lvc:CartesianChart>
</Grid>
<Grid>
<lvc:CartesianChart Series="{Binding SeriesCollection2}" LegendLocation="Right" Margin="792,160,9.8,238" >
<lvc:CartesianChart.AxisY>
<lvc:Axis Title="Sales" LabelFormatter="{Binding YFormatter2}"></lvc:Axis>
</lvc:CartesianChart.AxisY>
<lvc:CartesianChart.AxisX>
<lvc:Axis Title="Month" Labels="{Binding Labels2}"></lvc:Axis>
</lvc:CartesianChart.AxisX>
</lvc:CartesianChart>
</Grid>
C#:
public MainWindow(){
cartchartinit();
cartchartinit2();
}
private void cartchartinit2()
{
SeriesCollection2 = new SeriesCollection
{
new LineSeries
{
Title = "Series 1",
Values = new ChartValues<double> { 4, 6, 5, 2 ,7 }
},
new LineSeries
{
Title = "Series 2",
Values = new ChartValues<double> { 6, 7, 3, 4 ,6 }
}
};
Labels2 = new[] { "Jan", "Feb", "Mar", "Apr", "May" };
YFormatter2 = value => value.ToString("C");
//modifying the series collection will animate and update the chart
SeriesCollection2.Add(new LineSeries
{
Values = new ChartValues<double> { 5, 3, 2, 4 },
LineSmoothness = 0 //straight lines, 1 really smooth lines
});
//modifying any series values will also animate and update the chart
SeriesCollection2[2].Values.Add(5d);
DataContext = this;
}
public SeriesCollection SeriesCollection2 { get; set; }
public string[] Labels2 { get; set; }
public Func<double, string> YFormatter2 { get; set; }
private void cartchartinit()
{
SeriesCollection = new SeriesCollection
{
new LineSeries
{
Title = "Average Vehicles Gap",
Values = null
},
/* new LineSeries
{
Title = "Avg Gap (Metre)",
Values = null
},*/
/*new LineSeries
{
Title = "Series 3",
Values = new ChartValues<double> { 4,2,7,2,7 },
PointGeometry = DefaultGeometries.Square,
PointGeometrySize = 15
}*/
};
Labels = null;
YFormatter = value => value.ToString("");
DataContext = this;
}
public SeriesCollection SeriesCollection { get; set; }
public string[] Labels { get; set; }
public Func<double, string> YFormatter { get; set; }
当我只使用 cartchartinit() 方法时,它可以工作。但是当我添加 cartchartinit2() 时,它只为后面的图表绘制图形。我做错了吗?
我们将不胜感激。
谢谢
【问题讨论】:
-
您可能已经注意到自己,但是在 MainWindow 类的其他相同属性的名称中添加数字后缀是一种不好的方法。如果您必须显示 10 个图表怎么办?您应该使用这三个属性创建一个单独的类,例如称之为 ChartViewModel。然后,您将创建此类的多个实例并将它们分配给多个 CartesianChart 控件的 DataContext。
-
这最好(并且几乎是自动地)通过将 CartesianChart 控件放在 ItemsControl 的 ItemTemplate 中来完成,它的 ItemsSource 属性绑定到 ChartViewModel 类的集合。见Data Templating Overview。
-
@Clemens 在摆弄并测试了您的建议之后,我发现问题出在 datacontext = 这在代码中设置了不止一次,这可能导致两个图表没有同时初始化。尽管如此,感谢您对数据模板方式的解释,这对我来说是新的,它实际上使我的代码更干净。
标签: asp.net wpf livecharts