Согласно вашему описанию, вы хотите добавить Picker для выбора элемента для фильтрации Collectionview, я прав?
Если да, я делаю один пример, который вы можете посмотреть:
<ContentPage
x:Class="demo3.collectionviewsample.Page2"
xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:d="http://xamarin.com/schemas/2014/forms/design"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d">
<ContentPage.Content>
<StackLayout>
<Picker
ItemDisplayBinding="{Binding .}"
ItemsSource="{Binding FilterOptions}"
SelectedItem="{Binding SelectedFilter}" />
<CollectionView ItemsSource="{Binding FilterSource}">
<CollectionView.ItemTemplate>
<DataTemplate>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding Name}" />
<Label Text="{Binding Role}" />
</StackLayout>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
</StackLayout>
</ContentPage.Content>
public partial class Page2 : ContentPage
{
public Page2()
{
InitializeComponent();
this.BindingContext = new ItemViewModel();
}
}
ViewModel:
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
public string Role { get; set; }
}
public class ItemViewModel:ViewModelBase
{
public ObservableCollection<string> FilterOptions { get; set; }
public ObservableCollection<Item> source { get; set; }
public List<Item> _FilterSource;
public List<Item> FilterSource
{
get { return _FilterSource; }
set
{
_FilterSource = value;
RaisePropertyChanged("FilterSource");
}
}
private string _SelectedFilter;
public string SelectedFilter
{
get { return _SelectedFilter; }
set
{
_SelectedFilter = value;
RaisePropertyChanged("SelectedFilter");
filteritems(SelectedFilter);
}
}
public ItemViewModel()
{
FilterOptions = new ObservableCollection<string>()
{
"All",
"Admin",
"Editor",
"Student"
};
source = new ObservableCollection<Item>()
{
new Item() { Id = 1, Name = "cherry", Role = "Admin" },
new Item() { Id = 2, Name = "barry", Role = "Admin" },
new Item() { Id = 3, Name = "json", Role = "Editor" },
new Item() { Id = 3, Name = "json", Role = "Editor" },
new Item() { Id = 5, Name = "Leo", Role = "Student" },
new Item() { Id = 6, Name = "Cole", Role = "Student" }
};
FilterSource = new List<Item>();
}
private void filteritems(string selecteditem)
{
FilterSource.Clear();
if(selecteditem=="All")
{
FilterSource = source.ToList();
}
else
{
FilterSource = source.Where(item => item.Role == selecteditem).ToList();
}
}
}
ViewModelBase - это класс, реализующий интерфейс INotifyPropertyChanged, для изменения данных.
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Снимок экрана: