Why doesn't this data binding work?

Posted by Qwertie on Stack Overflow See other posts from Stack Overflow or by Qwertie
Published on 2009-05-15T22:10:07Z Indexed on 2010/06/14 21:22 UTC
Read the original article Hit count: 280

Filed under:
|
|

I have a ViewModel class that contains a list of points, and I am trying to bind it to a Polyline. The Polyline picks up the initial list of points, but does not notice when additional points are added even though 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"));
	}
}

© Stack Overflow or respective owner

Related posts about .NET

Related posts about wpf