且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

带有ObservableCollection< T>的Silverlight ListBox和动态过滤器

更新时间:2022-10-30 17:06:59

你的答案是CollectionViewSource。而不是绑定到列表,绑定到一个CollectionViewSource的实例。



稍微退化的例子如下(我不知道你是否使用ViewModels,Locators等解决您的数据和列表。)



假设在您的标记中,您的资源中声明了一个CollectionViewSource,如下所示:

 < phone:PhoneApplicationPage.Resources> 
< CollectionViewSource x:Key =src/>
< / phone:PhoneApplicationPage.Resources>

然后,您的列表绑定如下所示:

 < ListBox x:Name =MyListBoxItemsSource ={Binding Source = {StaticResource src}}> 

最后,在代码中,您可以结婚列表和收藏视图源:

  var collectionView = this.Resources [src]作为CollectionViewSource; 
//检查null等等
collectionView.Source = observableCollectionThatIAmBindingTo;
collectionView.View.Filter = new Predicate< Object>(o =>((ItemType)o).IsActive);

此外,您可能需要查看Bea Stollnitz关于该主题的文章:



http://bea.stollnitz.com/blog /?p = 31



http://bea.stollnitz.com/blog/?p=392


Lets say I have this class:

public class MyData
{
    public bool IsActive{get;set;}
    public String Data1 {get;set;}
    public String Data2 {get;set;}
}

and an

ObservableCollection<MyData> data = new ObservableCollection<MyData>;
ListBox.ItemsSource = data;

Adding items to the ObservableCollectionworks as expected; however, I want to make sure that my listbox only displays items where IsActive is set to 'true' -- I can't use a Linq query to set the ItemsSource because then its not an ObservableCollection, its IEnumerable and does not do any update notifications to the listbox.

Your answer is CollectionViewSource. Instead of binding to the list, bind to an instance of CollectionViewSource.

A slightly degenerate example follows (I am not sure if you're using ViewModels, Locators, etc to resolve your data and your list.)

Assume in your markup you have a CollectionViewSource declared in your resources as follows:

<phone:PhoneApplicationPage.Resources>
    <CollectionViewSource x:Key="src"/>
</phone:PhoneApplicationPage.Resources>

Then your list binding looks like:

<ListBox x:Name="MyListBox" ItemsSource="{Binding Source={StaticResource src}}">

Finally, in code you can marry your list and your collection view source:

        var collectionView = this.Resources["src"] as CollectionViewSource;
        // Check for null, etc.
        collectionView.Source = observableCollectionThatIAmBindingTo;
        collectionView.View.Filter=new Predicate<Object>(o => ((ItemType)o).IsActive );

Additionally, you may want to check out Bea Stollnitz' articles on the topic at:

http://bea.stollnitz.com/blog/?p=31

http://bea.stollnitz.com/blog/?p=392