如何将附加行为添加到CollectionViewSource?

我正在尝试向CollectionViewSource添加附加行为,以便我可以在XAML中的视图模型上提供filterPredicate属性。

XAML如下所示:

     

但是,我收到一个错误:

 A 'Binding' cannot be set on the 'SetItemFilter' property of type 'CollectionViewSource'. A 'Binding' can only be set on a DependencyProperty of a DependencyObject. 

CollectionViewSource似乎是DependencyObject。 我不确定我做错了什么。

以下是行为代码:

 public static class CollectionViewSourceItemFilter { ///  /// Gets the property value. ///  public static Predicate GetItemFilter(CollectionViewSource collectionViewSource) { return (Predicate)collectionViewSource.GetValue(ItemFilter); } ///  /// Sets the property value. ///  public static void SetItemFilter(CollectionViewSource collectionViewSource, Predicate value) { collectionViewSource.SetValue(ItemFilter, value); } ///  /// The ItemFilter dependency property. ///  public static readonly DependencyProperty ItemFilter = DependencyProperty.RegisterAttached( "ItemFilter", typeof(Predicate), typeof(ItemFilterBehavior), new UIPropertyMetadata(null, OnItemFilterChanged)); private static void OnItemFilterChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e) { CollectionViewSource collectionViewSource = depObj as CollectionViewSource; if (collectionViewSource == null) return; if (!Equals(e.NewValue, e.OldValue)) { var newFilter = (Predicate)e.NewValue; // Remove any previous filter. ItemFilterBehavior oldBehavior; if (behaviors.TryGetValue(collectionViewSource, out oldBehavior)) { oldBehavior.Unregister(); behaviors.Remove(collectionViewSource); } if (newFilter != null) behaviors.Add(collectionViewSource, new ItemFilterBehavior(collectionViewSource, newFilter)); } } private class ItemFilterBehavior { public ItemFilterBehavior(CollectionViewSource collectionViewSource, Predicate filter) { _collectionViewSource = collectionViewSource; _filter = filter; _collectionViewSource.Filter += collectionViewSource_Filter; } void collectionViewSource_Filter(object sender, FilterEventArgs e) { e.Accepted = _filter(e.Item); } public void Unregister() { _collectionViewSource.Filter -= collectionViewSource_Filter; } private readonly CollectionViewSource _collectionViewSource; private readonly Predicate _filter; } private static readonly IDictionary behaviors = new ConcurrentDictionary(); } 

在问题中发布行为代码让我弄明白了。 我的DependencyProperty使用ItemFilterBehavior而不是CollectionViewSourceItemFilter作为所有者类型。