我建议不要将ObservableCollection作为“Items”依赖属性的类型。
这里使用ObservableCollection的原因(我猜)是为了在分配属性值时使UserControl能够附加“CollectionChanged”处理程序。但是,ObservableCollection过于特定。
The approach used in WPF (for example, in
ItemsControl.ItemsSource) is to define a basic interface type (such as
IEnumerable
) and, when the property is assigned a value, determine if the value collection implements certain more specific interfaces. At a minimum, this would include
INotifyCollectionChanged, but the collection may also implement
ICollectionView and
INotifyPropertyChanged. None of these interfaces are mandatory, which allows your dependency property to bind to various types of collections, ranging from a simple array to a complex
ItemCollection.
Your
OnItemsChanged
property change callback would then resemble the following:
private static void OnItemsChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
MyGrid grid = obj as MyGrid;
if (grid != null)
{
var oldCollectionChanged = e.OldValue as INotifyCollectionChanged;
var newCollectionChanged = e.NewValue as INotifyCollectionChanged;
if (oldCollectionChanged != null)
{
oldCollectionChanged.CollectionChanged -= grid.OnItemsCollectionChanged;
}
if (newCollectionChanged != null)
{
newCollectionChanged.CollectionChanged += grid.OnItemsCollectionChanged;
}
}
}
private void OnItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
}