1
votes

I have a grouped listview in my project. When I try to add the ItemSelected event for the listview I am getting the following error:

System.InvalidCastException: 'Specified cast is not valid.'

My Code

XAML:

<ListView
  ItemsSource="{Binding AllItems,Mode=TwoWay}">
    <ListView.GroupHeaderTemplate>
        <DataTemplate>
            <ViewCell>
            //header label
                <Label/>
            </ViewCell>
        </DataTemplate>
    </ListView.GroupHeaderTemplate>
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
            <ViewCell.View>
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="40*"/>
                        <ColumnDefinition Width="60*"/>
                    </Grid.ColumnDefinitions>

                    <StackLayout
                        Grid.Column="0"
                        BackgroundColor="#f9f9f9"
                        Orientation="Vertical">

                        //Items
                    </StackLayout>

                        <Label Grid.Column="1"/>
                    </Grid>
                </ViewCell.View>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
    <ListView.Footer>
        <Label/>
    </ListView.Footer>
</ListView>

Viewmodel

public ObservableCollection<EventsHB> AllItems
{
    get
    {
        return _allItems;
    }
    set
    {
        _allItems = value;
        OnPropertyChanged("AllItems");
    }
}

XAML.CS

MyEventsListview.ItemSelected += (object sender, SelectedItemChangedEventArgs e) =>
{
    var selectedItem = (EventsHB) e.SelectedItem;
    if (selectedItem != null)
    {
        //loading the next page
    }
    MyEventsListview.SelectedItem = null;
};
1
Can you see in debugger what SelectedItem is?Miamy
@Miamy At that line app breaks with this exceptionSreejith Sree
So you should to put a breakpoint on this line and see the variable valueMiamy
@Miamy Got the solution, I have added it as my answer.Sreejith Sree

1 Answers

0
votes

Got solution from my XF thread.

This is because EventsHB is your group item but the selected item is a part of your group item you can't cast it to EventsHB. i.e.

// Your EventsHB looks like
public class EventsHB : ObservableCollection<Model>
{
   public string Title { set; get; }
}

Then the type of the selected item is Model.