Why does this data binding not work?

I have a ViewModel class that contains a list of points, and I'm trying to associate it with a polyline. The polyline takes the original list of points, but does not notice when additional points are added, although I implement INotifyPropertyChanged. What's wrong?

<StackPanel> <Button Click="Button_Click">Add!</Button> <Polyline x:Name="_line" Points="{Binding Pts}" Stroke="Black" StrokeThickness="5"/> </StackPanel> 

C # side:

 // code-behind _line.DataContext = new ViewModel(); private void Button_Click(object sender, RoutedEventArgs e) { // The problem is here: NOTHING HAPPENS ON-SCREEN! ((ViewModel)_line.DataContext).AddPoint(); } // ViewModel class public class ViewModel : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public PointCollection Pts { get; set; } public ViewModel() { Pts = new PointCollection(); Pts.Add(new Point(1, 1)); Pts.Add(new Point(11, 11)); } public void AddPoint() { Pts.Add(new Point(25, 13)); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Pts")); } } 
+4
source share
3 answers

Change the PointCollections property to the dependency property:

 public PointCollection Pts { get { return (PointCollection)GetValue(PtsProperty); } set { SetValue(PtsProperty, value); } } // Using a DependencyProperty as the backing store for Pts. This enables animation, styling, binding, etc... public static readonly DependencyProperty PtsProperty = DependencyProperty.Register("Pts", typeof(PointCollection), typeof(ViewModel), new UIPropertyMetadata(new PointCollection())); 

By the way. You do not need to fire the PropertyChanged event.

Sorry, and your object should inherit from DependencyObject

  public class ViewModel : DependencyObject { //... } 
+1
source

It is likely that since it is tied to a collection, it will need something like ObservableCollection<T> . What happens if you switch from PointCollection to ObservableCollection<Point> ?

+4
source

I got it as POCO by doing INotifyCollectionChanged instead of INotifyPropertyChanged.

+1
source

All Articles