Is possibile to hide elementis from ObservableCollection? Net MAUI

109 Views Asked by At

I'm using MVVM and Ms Toolkit.

I'm showing a collection within a CollectionView, but I would like to hide deleted items (set by a flag on model).

This why I'm using a global "save" procedure in a tabs page but it would be nice to hide what I've deleted.

I've tried with Where(p => p.deleted == false) but:

  1. won't work on ObservableColletion
  2. return a IEnumerable

Searched Google & Docs already.

2

There are 2 best solutions below

0
H.A.H. On BEST ANSWER

I've tried with Where(p => p.deleted == false) but:

1.won't work on ObservableColletion

2.return a IEnumerable

Returning IEnumerable is not a problem, because it can be converted to list:

https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.tolist?view=net-8.0

It will work on ObservableCollection, because you have constructor that takes list as parameter.

https://learn.microsoft.com/en-us/dotnet/api/system.collections.objectmodel.observablecollection-1.-ctor?view=net-8.0#system-collections-objectmodel-observablecollection-1-ctor(system-collections-generic-list((-0)))

Also, even if anything of the above was not true, you can always:

  1. Suppress notifications
  2. Clear collection and add items.
  3. Turn notifications on.

I do it all the time.

6
Julian On

Since you're not showing your code, I'll provide a more generic answer.

You can add an IsDeleted property to your model class:

public partial class MyModel : ObservableObject
{
    [ObservableProperty]
    private string _name;

    [ObservableProperty]
    private bool _isDeleted;
}

Then, in your ViewModel you would keep your ObservableCollection<MyModel>:

public partial class MyViewModel : ObservableObject
{
    [ObservableProperty]
    private ObservableCollection<MyModel> _myItems;
}

Finally, in your View, you would then bind to the IsDeleted property and use the InvertedBoolConverter from the MCT to show or hide deleted items:

<ContentPage.Resources>
    <mct:InvertedBoolConverter x:Key="InvertedBoolConverter" />
</ContentPage.Resources>

<CollectionView ItemsSource="{Binding MyItems}">
    <CollectionView.ItemTemplate>
        <DataTemplate x:DataType="models:MyModel">
            <Label
                Text="{Binding Name}"
                IsVisible="{Binding IsDeleted, Converter={StaticResource InvertedBoolConverter}}" />
        </DataTemplate>
    </CollectionView.ItemTemplate>
</CollectionView>