我是MVVM的新手。目前,我所有的代码都是在链接到XAML的.cs文件中编写的。我想切换到MVVM,但遇到了困难。我将尝试解释原因:
我在.cs文件中指定了许多不同的图表控件和输入数据,我直接访问图表对象,并通过编程使用它的属性为图表添加点。
示例:
foreach (var group in qcv.Groups)
{
AreaSeries areaSeries = new AreaSeries();
areaSeries.CombineMode = Telerik.Charting.ChartSeriesCombineMode.Stack;
areaSeries.ValueBinding = new PropertyNameDataPointBinding("Rev");
areaSeries.CategoryBinding = new PropertyNameDataPointBinding("Date");
areaSeries.ItemsSource = group as IEnumerable;
RadChart1.Series.Add(areaSeries);
}
但只要我切换到MVVM,ViewModel文件中的RadChart1
对象就无法访问。我如何使它在ViewModel类中可见,或者您可以建议更好的方法,如何在不更改代码的情况下获取该对象并为图表提供输入?
我的XAML文件:
<UserControl x:Class="FrontEnd.RevenueChart"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:FrontEnd"
mc:Ignorable="d" xmlns:telerik="http://schemas.telerik.com/2008/xaml/presentation" HorizontalAlignment="Stretch" >
<UserControl.DataContext>
<local:RevenueChartViewModel/>
</UserControl.DataContext>
<Grid>
<telerik:RadCartesianChart HorizontalAlignment="Stretch" x:Name="RadChart1" Palette="Metro" Zoom="10,1">
<telerik:RadCartesianChart.HorizontalAxis>
<telerik:CategoricalAxis/>
</telerik:RadCartesianChart.HorizontalAxis>
<telerik:RadCartesianChart.VerticalAxis>
<telerik:LinearAxis/>
</telerik:RadCartesianChart.VerticalAxis>
<telerik:RadCartesianChart.Behaviors>
<telerik:ChartPanAndZoomBehavior ZoomMode="Both">
</telerik:ChartPanAndZoomBehavior>
</telerik:RadCartesianChart.Behaviors>
</telerik:RadCartesianChart>
</Grid>
</UserControl>
从视图模型访问视图控件是MVVM领域的一大禁忌。你必须颠倒你的想法:与其把东西添加到Series
,不如把Series
绑定到东西上。使用SeriesMapping
s获取图表控件以将您的组转换为系列。下面是一些让你开始的即兴代码:
<telerik:RadCartesianChart HorizontalAlignment="Stretch"
Palette="Metro" Zoom="10,1"
Series="{Binding Groups}"><!-- <=== this is the important part -->
<telerik:RadChart.SeriesMappings>
<telerikCharting:SeriesMapping LegendLabel="Product Sales">
<telerikCharting:SeriesMapping.SeriesDefinition>
<telerikCharting:AreaSeriesDefinition/>
</telerikCharting:SeriesMapping.SeriesDefinition>
<telerikCharting:SeriesMapping.ItemMappings>
<telerikCharting:ItemMapping DataPointMember="XCategory" FieldName="Date"/>
<telerikCharting:ItemMapping DataPointMember="YValue" FieldName="Rev"/>
</telerikCharting:SeriesMapping.ItemMappings>
</telerikCharting:SeriesMapping>
</telerik:RadChart.SeriesMappings>
...