我正在关注如何创建基本麻雀图的this教程。基本上涉及创建ViewModel类并在图表的DataContext中设置ViewModel。
ViewModel:
//Create a model
public class Model
{
public double X { get; set; }
public double Y { get; set; }
public Model(double x,double y)
{
X = x;
Y = y;
}
}
// Create a ViewModel
public class ViewModel
{
public ObservableCollection<Model> Collection { get; set; }
public ViewModel()
{
Collection = new ObservableCollection<Model>();
GenerateDatas();
}
private void GenerateDatas()
{
this.Collection.Add(new Model(0, 1));
this.Collection.Add(new Model(1, 2));
this.Collection.Add(new Model(2, 3));
this.Collection.Add(new Model(3, 4));
}
}
XAML:
//Use the viewmodel in the Sparrow Chart
<sparrow:SparrowChart>
<sparrow:SparrowChart.DataContext>
**<local:ViewModel/>**
</sparrow:SparrowChart.DataContext>
<sparrow:SparrowChart.XAxis>
<sparrow:LinearXAxis/>
</sparrow:SparrowChart.XAxis>
<sparrow:SparrowChart.YAxis>
<sparrow:LinearYAxis/>
</sparrow:SparrowChart.YAxis>
<sparrow:LineSeries PointsSource="{Binding Collection}" XPath="X" YPath="Y"/>
如何定义 local:命名空间,然后在其中包含ViewModel,以便它在DataContext中运行良好?
答案 0 :(得分:0)
将以下行添加到窗口的XAML代码中
xmlns:local="clr-namespace:Here.Comes.Your.Namespace"
就我而言,它看起来像
<Window x:Class="MyProgram.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sparrow="http://sparrowtoolkit.codeplex.com/wpf"
xmlns:local="clr-namespace:MyProgram"
Title="My Program" Height="306" Width="736" MinWidth="680" MinHeight="440">
同样要实际绑定集合,您可以使用它向SparrowChart提供数据,使用ViewModel实例设置图表的DataContext。
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public sealed partial class MainWindow
{
ViewModel myViewModel;
public MainWindow()
{
...
myViewModel = new ViewModel();
mySparrowChart.DataContext = myViewModel;
}
}
SparrowChart的控制名称当然是mySparrowChart
(
<sparrow:SparrowChart Name="mySparrowChart">
)。