Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

In .NET MAUI, the content of an ObservableCollection can be presented using a ListView control.

Here are the steps to present the content of an ObservableCollection in .NET MAUI using a ListView control:

  1. Define an ObservableCollection of the data type that you want to display in the ListView control. For example, if you want to display a list of string values, define an ObservableCollection<string> object.

  2. Create a ListView control in the XAML markup of your MAUI page.

  3. Set the ItemsSource property of the ListView control to the ObservableCollection that you created in step 1.

  4. Define the layout of each cell in the ListView using the ItemTemplate property of the ListView control.

  5. Within the ItemTemplate, you can define the layout of each cell using various MAUI UI controls, such as Label, Image, or other UI elements.

  6. Run your MAUI app to see the content of the ObservableCollection displayed in the ListView control.

Here is an example of XAML markup for presenting the content of an ObservableCollection in .NET MAUI using a ListView control:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="MyApp.MainPage"
             xmlns:local="clr-namespace:MyApp">

    <ContentPage.Resources>
        <local:MyViewModel x:Key="viewModel" />
    </ContentPage.Resources>

    <StackLayout>
        <ListView ItemsSource="{Binding Source={StaticResource viewModel}, Path=MyList}">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <StackLayout>
                            <Label Text="{Binding}" />
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </StackLayout>

</ContentPage>

In the example above, the MainPage class is associated with a MyViewModel object that contains an ObservableCollection of string values named MyList. The ListView control is bound to the MyList collection using the ItemsSource property. The ItemTemplate defines the layout of each cell in the ListView, which in this case contains a simple Label control that displays the string value.