xamarinxamarin.formsfreshmvvm

Xamarin Forms - SelectionChangedCommand not firing for CollectionView


The code below shows a simple example of a CollectionView. I am not receiving the event for the SelectionChangedCommand. Can someone see what I am doing wrong?

btw, the complete source for this can be found on GitHub here.

MainPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
                 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
                 xmlns:local="clr-namespace:ControlDemo"
                 x:Class="ControlDemo.MainPage">

    <StackLayout>
        <CollectionView SelectionMode ="Single"
                        ItemsSource="{Binding Tags}"
                        SelectionChangedCommand="{Binding SelectedTagChanged}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <StackLayout>
                        <Label Text="{Binding .}" />
                    </StackLayout>
                </DataTemplate>
            </CollectionView.ItemTemplate>
        </CollectionView>
    </StackLayout>

</ContentPage>

MainPageModel.cs

public class MainPageModel : FreshBasePageModel
{
    public override void Init(object initData)
    {
        Tags = new List<string>() { "A", "B", "C" };
        base.Init(initData);
    }

    public List<string> Tags { get; set; }

    public Command SelectedTagChanged
    {
        get
        {
            return new Command(() =>
            {
            });
        }
    }
}

Solution

  • I use your code and created a demo on my side, I add the widthRequest and HeightRequest to make the collectionView work:

     <CollectionView            
                  HeightRequest="170" 
                  WidthRequest="200"                        
                  SelectionMode="Single" 
                  SelectionChangedCommand="{Binding SelectedTagChangedCommand}"
                  ItemsSource="{Binding Tags}"      
             >
    

    The SelectionChangedCommand did triggered after I click different items in the CollectionView.

    I uploaded a sample here and you can check it: collectionView-selectItemChanged-xamarin.forms