WPF CollectionViewSource Multiple Views?

后端 未结 2 1421
生来不讨喜
生来不讨喜 2020-12-09 09:50

I\'ve written a Custom WPF Control with search extension, let\'s name it MyControl. The Control is a descendent of an ItemsControl class.

2条回答
  •  隐瞒了意图╮
    2020-12-09 10:47

    In situations like this you would generally want to create a separate ICollectionView instance for each differently filtered usage of the collection. It's not a good idea to use a specific implementation of ICollectionView since it's possible for the CollectionView type needed to change if the ItemsSource is bound to a different type of collection. Using

     ICollectionView filteredView = new CollectionViewSource { Source=newValue }.View;
    

    will give you an ICollectionView that's the correct type automatically.

    Unfortunately, what you may find in this case is that it is very difficult to apply a different collection to the ItemsPresenter of your custom control since all of that magic is done for you by the base ItemsControl class and relies on the ItemsSource/Items properties which it manages. This happens when using something similar to ItemsControl's default template.

    If you are in fact using a separate ListBox control (and TemplateBinding all the ItemsSource properties if you need them) inside your ControlTemplate then you should be able to simply add a new ICollectionView DP (I'd recommend read-only) on your control to hold your filtered version of the collection and bind the template ListBox's ItemsSource to that new property.

提交回复
热议问题