DependencyProperty忽略OnPropertyChanged();

时间:2011-11-14 21:39:15

标签: c# .net wpf listview binding

我有PointsListViewPointContainer: INotifyPropertyChanged, ICollection<Point>

public class PointContainer: INotifyPropertyChanged, ICollection<Point>
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(PropertyChangedEventArgs e)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, e);
        }

        public IEnumerable<Point> Points
        {
            get
            {
                return points.Values;
            }
        }

        public void Clear()
        {
            points.Clear();
            OnPropertyChanged(new PropertyChangedEventArgs("Points"));
        }

...

}

为了可靠性,我从代码中做了一个绑定:

private void BindPointContainerToListView()
{
   Binding binding = new Binding();
   binding.Source = PointContainer;
   binding.Path = new PropertyPath("Points");
   PointsListView.SetBinding(ListView.ItemsSourceProperty, binding);
}

为什么更改PointContainer时不会自动更新PointsListView.ItemsSource。 PointsListView.Items.Refresh();解决问题,但为什么不能自动工作?我做错了什么?

1 个答案:

答案 0 :(得分:3)

如果您希望在添加或删除某个点时进行更新,则需要实施INotifyCollectionChanged。 (ObservableCollection<T>提供了一个为您执行此操作的集合实现...)

如果您希望在更改某个点的值时进行更新,那么您的Point课程必须实施INotifyPropertyChanged