0

I have a list with a converter like so

   <ListView ItemsSource="{Binding Availability, Converter={StaticResource AvailabilityConverter}}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ContentView>
                            <ContentView.Content>
                                <StackLayout>
                                    <Label Text="{Binding DateTime.TimeOfDay}" />                                  
                                </StackLayout>
                            </ContentView.Content>
                        </ContentView>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

Here is the converter

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value is IEnumerable<Availability>)
        {
            var availability = (List<Availability>)value;

            foreach (var day in availability)
            {
                //Manipulate the list in here
            }

            return availability;
        }

        return value;
    }

Availability is a list of DateTimes

I want to be able to write some business logic in the converter to manipulate the list in here before returning it however i get a System.InvalidCastException when it executed.

  • which specific line is causing the cast exception? You are testing for IEnumerable but casting to List - not all IEnumerables are Lists – Jason Apr 29 '19 at 16:02
  • when you convert IEnumerable to List , you could `List asList= enumerable.Cast().ToList() ` like this link https://stackoverflow.com/questions/7617771/converting-from-ienumerable-to-list/31487702 – Leon Apr 30 '19 at 07:21
  • I get the System.InvalidCastException when the method finishes executing, var availability = (List)value; does not cause any issues. Even if i changed this to var availability = (IEnumerable)value; it will still give me System.InvalidCastException when the method finishes executing – Ryan Stuart Apr 30 '19 at 08:22

1 Answers1

0

I think the exception comes from your xaml which is malformed. You're using a custom cell, it's must derive from ViewCell.

You xaml must looks like this:

<ListView ItemsSource="{Binding Availability, Converter={StaticResource AvailabilityConverter}}">
  <ListView.ItemTemplate>
     <DataTemplate>
        <ViewCell>
            <ContentView>
                <ContentView.Content>
                    <StackLayout>
                        <Label Text="{Binding DateTime.TimeOfDay}" />                                  
                    </StackLayout>
                </ContentView.Content>
            </ContentView>
        </ViewCell>
    </DataTemplate>
</ListView.ItemTemplate>