[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;
        }
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,188 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,608 questions
{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