我如何绑定Chart的PointCollection数据?

时间:2013-04-11 08:56:23

标签: silverlight xaml data-binding

我在silverlight中有这个简单的图表:

<toolkit:Chart HorizontalAlignment="Left" Margin="0,10,0,0" Title="Chart Title" VerticalAlignment="Top" Height="280" Width="390" Name="MyChart">
            <toolkit:ColumnSeries DependentValuePath="X" IndependentValuePath="Y">
                <toolkit:ColumnSeries.ItemsSource>
                    <PointCollection x:Name="PointColl">
                        <Point>1,10</Point>
                        <Point>2,20</Point>
                        <Point>3,30</Point>
                        <Point>4,40</Point>
                    </PointCollection>
                </toolkit:ColumnSeries.ItemsSource>
            </toolkit:ColumnSeries>
        </toolkit:Chart>

在代码中设置数据绑定,如下所示:

        private ObservableCollection<Point> _myPointCollection = new ObservableCollection<Point>();
        public ObservableCollection<Point> MyPointCollection { get { return _myPointCollection; } }

        public MainPage()
        {
            InitializeComponent();

            rand = new Random(); 

            MyPointCollection.Add( new Point(0, rand.Next(0, 50)));
            MyPointCollection.Add( new Point(0, rand.Next(1, 50)));    
            MyPointCollection.Add( new Point(0, rand.Next(2, 50)));
            MyPointCollection.Add( new Point(0, rand.Next(3, 50)));

            MyChart.DataContext = this;
        }

但是在xaml中我告诉哪里绑定数据?

1 个答案:

答案 0 :(得分:1)

尝试:

<toolkit:Chart HorizontalAlignment="Left" Margin="0,10,0,0" Title="Chart Title" VerticalAlignment="Top" Height="280" Width="390" Name="MyChart">
        <toolkit:ColumnSeries DependentValuePath="X" IndependentValuePath="Y" ItemsSource={Binding MyPointCollection}>

    </toolkit:Chart>

但是,如果您希望在更改整个MyPointCollection属性时更新图表,则必须提升PropertyChanged事件。当您向集合添加或删除点时,您不必这样做。