[risolto] CollectionView.IndexOf .NET MAUI

MacSlacky 20 Reputation points
2023-05-15T16:01:10.4733333+00:00

I wanted to use CollectionView.IndexOf to retrieve the index of the specified item but indexof does not exist

if I add using System.Windows.Data;

var collectionView = (CollectionView)container;

gives me error converting Microsoft.Maui with System.Windows

this is what I would like to accomplish

protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
       {
            var collectionView = (System.Windows.Data.CollectionView)container;
            var index = collectionView.ItemsSource.IndexOf(item);
            return index%2 == 0 ? unoTemplate : dueTemplate;
        }
Developer technologies | .NET | .NET MAUI
Developer technologies | C#
{count} votes

1 answer

Sort by: Most helpful
  1. MacSlacky 20 Reputation points
    2023-05-26T12:48:59.07+00:00

    certainly, the error was in casting an object to a type not compatible with the object itself.

    this is the instruction that fixed my problem
    IList collection = (IList)collectionView.ItemsSource;

    I put the complete code below

    protected override DataTemplate OnSelectTemplate(object item, BindableObject container)
            {
                var collectionView = (CollectionView)container;
                IList collection = (IList)collectionView.ItemsSource;
                var index = collection.IndexOf(item);
                return index%2==0 ? unoTemplate : dueTemplate;
            }
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.