I'm still learning C# by developing a small UWP app. Basically my app fetches my owned Steam games and adds them asynchronously to an ObservableCollection. Which adds the games to the Gridview.
XAML:
<GridView
x:Name="BasicGridView"
ItemsSource="{Binding}"
ItemTemplate="{StaticResource ImageTemplate}"
IsItemClickEnabled="True"
ItemClick="BasicGridView_ItemClick"
SelectionMode="Single"
Margin="15, 0, 0, 0"
>
<GridView.ItemContainerStyle>
<Style TargetType="GridViewItem">
<Setter Property="Margin" Value="0, 15, 15, 0"/>
</Style>
</GridView.ItemContainerStyle>
</GridView>
C# code:
// My games list
public ObservableCollection<Game> OwnedGames { get; set; }
// Binding my games list to the GridView
BasicGridView.DataContext = OwnedGames;
Now my next step is to add filtering. After some search, it seems a solution is to use a CollectionViewSource.
This is what I ended up with:
public ICollectionView OwnedGamesView { get; set; }
CollectionViewSource OwnedGamesViewSource = new CollectionViewSource();
OwnedGamesViewSource.Source = OwnedGames;
OwnedGamesView = OwnedGamesViewSource.View;
Since I would use a CollectionView now, I changed the Datacontext of the GridView like this:
BasicGridView.DataContext = OwnedGamesView;
When running the app, everything still works like this, so the last step would have been to perform the filtering itself:
OwnedGamesView.Filter(...);
However this method doesn't exist in my case. It isn't listed on the ICollectionView API reference for UWP: https://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.data.icollectionview?view=winrt-20348
So I am wondering how I can still make this work within an UWP app? Or what a possible alternative is?
I hope my question is clear? Thanks in advance! :)
CodePudding user response:
Filtering using a CollectionViewSource
is not done on the resulting View
collection, but the CollectionViewSource
instance itself. Add an event listener to the CollectionViewSource.Filter
event. See an example here.
CodePudding user response:
However this method doesn't exist in my case. It isn't listed on the ICollectionView API reference for UWP
ICollectionView
does not contain Filter
, for your requirement, you could use Microsoft.Toolkit
AdvancedCollectionView class to approach. It contains Filter
property, you could use it to filter the collection and set SortDescriptions
.
var acv = new AdvancedCollectionView(oc);
// Let's filter out the integers
int nul;
acv.Filter = x => !int.TryParse(((Person)x).Name, out nul);
// And sort ascending by the property "Name"
acv.SortDescriptions.Add(new SortDescription("Name", SortDirection.Ascending));
// AdvancedCollectionView can be bound to anything that uses collections. In this case there are two ListViews, one for the original and one for the filtered-sorted list.
RightList.ItemsSource = acv;