为什么这个数据绑定不起作用?

时间:2009-05-15 22:10:07

标签: .net wpf data-binding binding

我有一个包含点列表的ViewModel类,我试图将它绑定到折线。 Polyline选择了初始的点列表,但是即使我实现了INotifyPropertyChanged,也没有注意到添加其他点的时间。怎么了?

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

C#方:

// 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"));
    }
}

3 个答案:

答案 0 :(得分:4)

很可能因为它绑定到集合,所以它需要像ObservableCollection<T>这样的东西。如果您从PointCollection切换到ObservableCollection<Point>会怎样?

答案 1 :(得分:1)

将PointCollections属性更改为依赖项属性:

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()));

BTW执行此操作,您无需触发PropertyChanged事件。

哦对不起,你的对象需要从DependencyObject继承

    public class ViewModel : DependencyObject 
{ 
//... 
}

答案 2 :(得分:1)

我通过实现INotifyCollectionChanged而不是INotifyPropertyChanged让它作为POCO工作。