Jason94
Jason94

Reputation: 13610

How can I data bind Chart's PointCollection?

I have this simple Chart in 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>

And setup the databinding in the code like this:

        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;
        }

But where in the xaml to i tell where to bind the data?

Upvotes: 0

Views: 222

Answers (1)

Boluc Papuccuoglu
Boluc Papuccuoglu

Reputation: 2346

Try:

<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>

But, if you want the chart to update when you change the whole MyPointCollection property, you will have to Raise the PropertyChanged event. You don't have to do that when you add or remove points to the collection, tho.

Upvotes: 1

Related Questions