falukky
falukky

Reputation: 1139

Filter ObservableCollection and bind the new results

So I have this ObservableCollection:

ObservableCollection<ClipboardItem> Clipboards

This ObservableCollection binding into my ListView:

<ListView ItemsSource="{Binding Clipboards}"/>

And in my application I have this TextBox to allow the user to insert string to search for specific string inside my ListView and I want to filter all the result:

public void Execute(object? parameter)
        {
            TextBox textBox = parameter as TextBox;
            if (textBox != null)
            {
                var text = textBox.Text;
                var filteredItems = ViewModel.Clipboards.Where(x => x.Text.Contains(text)).ToList();
            }
        }

So this filteredItems is the new collection I want to bind into my ListView. What is the best approach to do that ?

I was thinking to move the original ObservableCollection collection into new collection, Bind the filtered list and in case the user clear the TextBox bind again the original ObservableCollection collection.

Upvotes: 0

Views: 185

Answers (1)

mm8
mm8

Reputation: 169200

You could store the original unfiltered collection in a variable and then either add and remove items from the filtered source collection property or replace it alltogether.

Something like this:

private readonly ClipboardItem[] allClipboards;
...

public ObservableCollection<ClipboardItem> Clipboards { get; }
    = new ObservableCollection<ClipboardItem>

public void Execute(object? parameter)
{
    TextBox textBox = parameter as TextBox;
    if (textBox != null)
    {
        var text = textBox.Text;
        var filteredItems = new HashSet<ClipboardItem>(allClipboards.Where(x => x.Text.Contains(text)));

        foreach (var item in Clipboards)
            if (!filteredItems.Contains(item))
                Clipboards.Remove(item);

        foreach (var item in filteredItems)
            if (!Clipboards.Contains(item))
                Clipboards.Add(item);
    }
}

Upvotes: 1

Related Questions