Link a single collection to multiple tabs with filters

In my small WPF project, I have TabControlthree tabs. On each tab there is ListBox. This project tracks the products we need to buy. (No, this is not homework, this is for my wife.) So, I have a list of ShoppingListItems, each of which has the property Nameand Needed: truewhen we need the item, and falseafter we buy it.

So, three tabs - that's all, bought and needed. All of them must point to the same ShoppingListItemCollection(which is inherited from ObservableCollection<ShoppingListItem>). But Bought should only show items where Needed is false, and Needed should only show items where Needed is true. (There are check boxes for items on the All tab.)

It doesn’t seem so difficult, but in a couple of hours I’m not going to figure it out. It seems that CollectionView or CollectionViewSource is what I need, but I can not do anything; I check and uncheck the boxes on the "All" tab, and the items on the other two tabs just sit looking at me.

Any ideas?

+3
source share
2 answers

You can use CollectionViewSource to reuse the original collection with a filter.

<Window.Resources>
    <CollectionViewSource x:Key="NeededItems" Source="{Binding Items}" Filter="NeededCollectionViewSource_Filter" />
    <CollectionViewSource x:Key="BoughtItems" Source="{Binding Items}" Filter="BoughtCollectionViewSource_Filter" />
</Window.Resources>

<TabControl>
    <TabItem Header="All">
        <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Items}" />
    </TabItem>
    <TabItem Header="Bought">
        <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource BoughtItems}}" />
    </TabItem>
    <TabItem Header="Needed">
        <ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource NeededItems}}" />
    </TabItem>
</TabControl>

The filter requires some code.

private void NeededCollectionViewSource_Filter(object sender, FilterEventArgs e)
{
    e.Accepted = ((ShoppingListItem) e.Item).Needed;
}

private void BoughtCollectionViewSource_Filter(object sender, FilterEventArgs e)
{
    e.Accepted = !((ShoppingListItem) e.Item).Needed;
}
+3
source

Here are some ideas:

  • When loading the “Purchased and necessary” tab, filter them yourself, creating new collections with the items you need or
  • , Needed
0

Source: https://habr.com/ru/post/1699310/


All Articles