You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: hub/apps/design/controls/listview-filtering.md
+112-87
Original file line number
Diff line number
Diff line change
@@ -3,142 +3,167 @@ description: Filter the items in your collection through user input.
3
3
title: Filtering collections
4
4
label: Filtering collections
5
5
template: detail.hbs
6
-
ms.date: 3/20/2024
6
+
ms.date: 3/29/2024
7
7
ms.topic: article
8
8
keywords: windows 10, uwp
9
9
pm-contact: anawish
10
10
---
11
11
12
12
# Filtering collections and lists through user input
13
-
If your collection displays many items or is heavily tied to user interaction, filtering is a useful feature to implement. Filtering using the method described in this article can be implemented to most collection controls, including [ListView](/windows/windows-app-sdk/api/winrt/microsoft.UI.Xaml.Controls.ListView), [GridView](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.gridview), and [ItemsRepeater](/uwp/api/microsoft.ui.xaml.controls.itemsrepeater?view=winui-2.2&preserve-view=true). Many types of user input can be used to filter a collection - such as checkboxes, radio buttons, and sliders - but this article will be focusing on taking text-based user input and using it to update a ListView in real time, according to the user's search.
13
+
14
+
If your collection displays many items or is heavily tied to user interaction, filtering is a useful feature to implement. Filtering using the method described in this article can be implemented with most collection controls, including [ListView](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.listview), [GridView](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.gridview), and [ItemsView](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.itemsview). Many types of user input can be used to filter a collection - such as checkboxes, radio buttons, and sliders - but this article demonstrates taking text-based user input and using it to update a ListView in real time, according to the user's search.
15
+
16
+
## Setting up the UI for filtering
17
+
18
+
To implement text filtering, your app will need a [ListView](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.listview) and a [TextBox](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.textbox) or other control that allows user input. The text that the user types into the TextBox is used as the filter; that is, only results that contain the user's text input will appear in the ListView. As the user types into the TextBox, the ListView constantly updates with filtered results.
14
19
15
20
> [!NOTE]
16
-
> This article will focus on filtering with a ListView. Please be aware that the filtering method can also be applied to other collections controls such as GridView, ItemsRepeater, or TreeView.
21
+
> This article demonstrates filtering with a ListView. However, the filtering that is demonstrated can also be applied to other collection controls such as GridView, ItemsView, or TreeView.
17
22
18
-
## Setting up the UI and XAML for filtering
19
-
To implement filtering, your app should have a ListView should appear alongside a TextBox or other control that allows for user input. The text that the user types into the TextBox will be used as the filter, i.e. only results containing their text input/search query will appear. As the user types into the TextBox, the ListView will constantly update with filtered results - specifically, everytime the text in the TextBox changes, even if by one letter, the ListView will go through its items and filter with that term.
23
+
The following XAML shows a UI with a simple ListView along with an accompanying TextBox. In this example, the ListView displays a collection of `Contact` objects. `Contact` is a class defined in the code-behind, and each `Contact` object has the following properties: `FirstName`, `LastName`, and `Company`.
20
24
21
-
The code below shows a UI with a simple ListView and its DataTemplate, along with an accompanying TextBox. In this example, the ListView displays a collection of Person objects. Person is a class defined in the code-behind (not shown in code sample below), and each Person object has the following properties: FirstName, LastName, and Company.
25
+
The user can type a filtering term into the TextBox to filter the list of `Contact` objects by last name. The TextBox has it's `x:Name` attribute set (`FilterByLastName`) so you can access the TextBox's [Text](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.textbox.text) property in the code-behind. You also handle it's [TextChanged](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.textbox.textchanged) event (`OnFilterChanged`). The TextChanged event occurs whenever the user types in the TextBox, letting you perform a filtering operation upon receiving user input.
22
26
23
-
Using the TextBox, users can type a search/filtering term to filter the list of Person objects by last name. Note that the TextBox is bound to a specific name (`FilterByLName`) and has its own TextChanged event (`FilteredLV_LNameChanged`). The bound name allows us to access the TextBox's content/text in the code-behind, and the TextChanged event will fire whenever the user types in the TextBox, allowing us to perform a filtering operation upon recieving user input.
27
+
For filtering to work, the ListView must have a data source that can be manipulated in the code-behind, such as an [ObservableCollection\<T>](/dotnet/api/system.collections.objectmodel.observablecollection-1). In this case, the ListView's [ItemsSource](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.itemscontrol.itemssource) property is assigned to an `ObservableCollection<Contact>`in the code-behind.
24
28
25
-
For filtering to work, the ListView must have a data source that can be manipulated in the code-behind, such as an `ObservableCollection<>`. In this case, the ListView's ItemsSource property is assigned to an `ObservableCollection<Person>` in the code-behind.
29
+
> [!TIP]
30
+
> This is a simplified version of the example in the ListView page of the [WinUI Gallery app](#get-the-sample-code). Use the WinUI Gallery app to run and view the full code, including the ListView's [DataTemplate](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.datatemplate) and the `Contact` class.
[Linq](/dotnet/csharp/programming-guide/concepts/linq/introduction-to-linq-queries) queries allow you to group, order, and select certain items in a collection. For filtering a list, we will be constructing a Linq query that only selects terms that match the user-inputted search query/filtering term, entered in the `FilterByLName` TextBox. The query result can be assigned to an [IEnumerable\<T>](/dotnet/api/system.collections.generic.ienumerable-1) collection object. Once we have this collection, we can use it to compare with the original list, removing items that don't match and adding back items that do match (in case of a backspace).
47
+
48
+
[Linq](/dotnet/csharp/programming-guide/concepts/linq/introduction-to-linq-queries) queries let you group, order, and select certain items in a collection. To filter a list, you construct a Linq query that selects only items that match the user-entered filtering term, entered in the `FilterByLastName` TextBox. The query result can be assigned to an [IEnumerable\<T>](/dotnet/api/system.collections.generic.ienumerable-1) collection object. Once you have this collection, you can use it to compare with the original list, removing items that don't match and adding back items that do match (in case of a backspace).
63
49
64
50
> [!NOTE]
65
-
> In order for the ListView to animate in the most intuitive way when adding and subtracting items, it's important to remove and add items to the ListView's ItemsSource collection itself, rather than create a new collection of filtered objects and assign that to the ListView's ItemsSource property.
51
+
> In order for the ListView to animate in the most intuitive way when adding and removing items, it's important to add and remove items in the ListView's [ItemsSource](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.itemscontrol.itemssource) collection itself, rather than create a new collection of filtered objects and assign that to the ListView's ItemsSource property.
66
52
67
-
To start, we'll need to initialize our original data source in a separate collection, such as a `List<T>` or `ObservableCollection<T>`. In this example, we have an `List<Person>` called `People`, that holds all of the Person objects shown in the ListView (population/initialization of this List is not shown in the code snippet below). We'll also need a list to hold the filtered data, which will constantly change every time a filter is applied. This will be an `ObservableCollection<Person>` called `PeopleFiltered`, and at initialization will have the same contents as `People`.
68
-
69
-
The code below performs the filtering operation through the following steps, shown in the code below:
70
-
- Set the ListView's ItemsSource property to `PeopledFiltered`.
71
-
- Define the TextChanged event, `FilteredLV_LNameChanged()`, for the `FilterByLName` TextBox. Inside this function, filter the data.
72
-
- To filter the data, access the user-inputted search query/filtering term through `FilterByLName.Text`. Use a Linq query to select the items in `People` whose last name contains the term `FilterByLName.Text`, and add those matching items into a collection called `TempFiltered`.
73
-
- Compare the current `PeopleFiltered` collection with the newly filtered items in `TempFiltered`, removing and adding items from `PeopleFiltered` where necessary.
74
-
- As items are removed and added from `PeopleFiltered`, the ListView will update and animate accordingly.
53
+
To start, you'll need to initialize your original data source in a separate collection, such as a [List\<T>](/dotnet/api/system.collections.generic.list-1). In this example, you have a `List<Contact>` called `allContacts` that holds all of the `Contact` objects that can potentially be shown in the ListView.
54
+
55
+
You'll also need a collection to hold the filtered data, which will constantly change every time a filter is applied. For this, you'll use an [ObservableCollection\<T>](/dotnet/api/system.collections.objectmodel.observablecollection-1) so that the ListView is notified to update whenever the collection changes. In this example, it's an `ObservableCollection<Person>` called `contactsFiltered`, and is the [ItemsSource](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.itemscontrol.itemssource) for the ListView. At initialization, it will have the same contents as `allContacts`.
56
+
57
+
The filtering operation is performed through these steps, shown in the following code:
58
+
59
+
- Set the ListView's [ItemsSource](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.itemscontrol.itemssource) property to `contactsFiltered`.
60
+
- Handle the [TextChanged](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.textbox.textchanged) event (`OnFilterChanged`) for the `FilterByLastName` TextBox. Inside this event handler function, filter the data.
61
+
- To filter the data, access the user-entered filtering term through the `FilterByLastName.Text` property. Use a [Linq](/dotnet/csharp/programming-guide/concepts/linq/introduction-to-linq-queries) query to select the items in `allContacts` where the last name contains the term in `FilterByLastName.Text`, and add those matching items into a collection called `filtered`.
62
+
- Compare the current `contactsFiltered` collection with the newly filtered items in `filtered`, removing and adding items in `contactsFiltered` where necessary to make it match `filtered`.
63
+
- As items are removed and added in `contactsFiltered`, the ListView updates and animates accordingly.
75
64
76
65
```csharp
77
66
usingSystem.Linq;
78
67
79
-
IList<Person>People;
80
-
ObservableCollection<Person>PeopleFiltered;
68
+
publicsealedpartialclassMainPage : Page
69
+
{
70
+
// Define Contact collection to hold all Contact objects.
71
+
IList<Contact> allContacts=newList<Contact>();
72
+
// Define an ObservableCollection<Contact> object to serve as the ListView's
73
+
// ItemsSource. This collection will get updated after the filters are used:
74
+
ObservableCollection<Contact> contactsFiltered;
81
75
82
76
publicMainPage()
83
77
{
84
-
// Define People collection to hold all Person objects.
85
-
// Populate collection - i.e. add Person objects (not shown)
// If the item in the filtered list is not currently in
142
+
// the ListView's source collection, add it back in.
143
+
if (!contactsFiltered.Contains(item))
126
144
{
127
-
PeopleFiltered.Add(item);
145
+
contactsFiltered.Add(item);
128
146
}
129
147
}
148
+
}
130
149
}
131
150
```
132
151
133
-
Now, as the user types in their filtering terms in the `FilterByLName` TextBox, the ListView will immediately update to only show the people whose last name contains the filtering term.
152
+
Now, as the user types in their filtering string in the `FilterByLastName` TextBox, the ListView immediately updates to show only the people whose last name contains the filtering string.
153
+
154
+
## Get the sample code
155
+
156
+
> [!div class="nextstepaction"]
157
+
> [Open the WinUI 3 Gallery app and see the ListView in action](winui3gallery:/item/ItemsView).
> For UWP: [!INCLUDE [winui-2-gallery](../../../includes/winui-2-gallery.md)]
134
162
135
-
## Next steps
136
163
137
-
### Get the sample code
138
-
> -[Open the WinUI 2 Gallery app and see the ListView](winui2gallery:/item/ListView) in action. [!INCLUDE [winui-2-gallery](../../../includes/winui-2-gallery.md)]
139
-
- Get the [WinUI 2 Gallery app (Microsoft Store)](https://www.microsoft.com/store/productId/9MSVH128X2ZT).
164
+
## Related articles
140
165
141
-
### Related articles
142
166
-[Lists](lists.md)
167
+
-[Items view](itemsview.md)
143
168
-[List view and grid view](listview-and-gridview.md)
0 commit comments