我仍在通過開發一個小型 UWP 應用程式來學習 C#。基本上,我的應用程式獲取我擁有的 Steam 游戲并將它們異步添加到 ObservableCollection。它將游戲添加到 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#代碼:
// My games list
public ObservableCollection<Game> OwnedGames { get; set; }
// Binding my games list to the GridView
BasicGridView.DataContext = OwnedGames;
現在我的下一步是添加過濾。經過一番搜索,似乎解決方案是使用 CollectionViewSource。
這就是我最終的結果:
public ICollectionView OwnedGamesView { get; set; }
CollectionViewSource OwnedGamesViewSource = new CollectionViewSource();
OwnedGamesViewSource.Source = OwnedGames;
OwnedGamesView = OwnedGamesViewSource.View;
因為我現在要使用 CollectionView,所以我像這樣更改了 GridView 的 Datacontext:
BasicGridView.DataContext = OwnedGamesView;
運行應用程式時,一切仍然如此,所以最后一步是執行過濾本身:
OwnedGamesView.Filter(...);
但是,這種方法在我的情況下不存在。它未列在 UWP 的 ICollectionView API 參考中:https ://docs.microsoft.com/en-us/uwp/api/windows.ui.xaml.data.icollectionview ? view = winrt-20348
所以我想知道如何才能在 UWP 應用程式中進行這項作業?或者可能的替代方案是什么?
我希望我的問題很清楚?提前致謝!:)
uj5u.com熱心網友回復:
使用 a 過濾CollectionViewSource不是在結果View集合上完成,而是在CollectionViewSource實體本身上完成。向事件添加事件偵聽器CollectionViewSource.Filter。請參閱此處的示例。
uj5u.com熱心網友回復:
但是,這種方法在我的情況下不存在。它未列在 UWP 的 ICollectionView API 參考中
ICollectionView不包含Filter,根據您的要求,您可以使用Microsoft.Toolkit AdvancedCollectionView類來接近。它包含Filter屬性,您可以使用它來過濾集合并設定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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/313978.html
