Hello,
Welcome to our Microsoft Q&A platform!
You can Use SelectionChangedCommand
and SelectionChangedCommandParameter
to transfer inboxList_SelectionChanged
to view model by Binding.
For example, I have following XAML layout.
<CollectionView x:Name="MyCollectionView" HeightRequest="170"
WidthRequest="200" ItemsSource="{Binding Monkeys}" SelectionMode="Single" SelectionChangedCommand="{Binding SelectedTagChangedCommand}" SelectionChangedCommandParameter="{Binding SelectedItem, Source={x:Reference MyCollectionView}}">
<CollectionView.ItemTemplate>
<DataTemplate>
<Grid Padding="10">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Label Grid.Column="1"
Text="{Binding Name}"
FontAttributes="Bold" />
</Grid>
</DataTemplate>
</CollectionView.ItemTemplate>
</CollectionView>
Here is layout background code.
public MainPage()
{
InitializeComponent();
this.BindingContext = new MyViewModel();
}
Here is my MyViewModel.cs
, When item was changed, SelectedTagChangedCommand
will be executed, we can get the select item by Monkey monkey= sender as Monkey;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Text;
using System.Windows.Input;
using Xamarin.Forms;
namespace App111
{
public class MyViewModel
{
public Command SelectedTagChangedCommand
{
get
{
return new Command((sender) =>
{
Monkey monkey= sender as Monkey;
Console.WriteLine("Select item in Colletionview"+ monkey.Name);
});
}
}
public ObservableCollection<Monkey> Monkeys { get; set; }
// public int { get; set; }
public MyViewModel()
{
Monkeys = new ObservableCollection<Monkey>();
Monkeys.Add(new Monkey() { Name = "test1" });
Monkeys.Add(new Monkey() { Name = "test2" });
Monkeys.Add(new Monkey() { Name = "test3" });
Monkeys.Add(new Monkey() { Name = "test4" });
}
}
public class Monkey
{
public string Name { get; set; }
}
}
Best Regards,
Leon Lu
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.