Categories
.NET .NET 8 .NET 9 .NET MAUI Android Blazor C# Code Desktop Developer Getting Started Hybrid iOS Learn macOS Mobile Tips Web Windows Xamarin Xamarin.Forms

.NET MAUI – BindableLayout

Lightweight Efficient Data-Bound Item Repeater

This is the second article in the newly started series titled Developer Tips, which offers concise hints to enhance productivity. The inaugural article is about Margin and Padding.

The BindableLayout functions as an item repeater, enabling an ILayout to interact with a data-bound IEnumerable.

This features five Attached properties.

  • EmptyView
  • EmptyViewTemplate
  • ItemsSource
  • ItemTemplate
  • ItemTemplateSelector

The BindableLayout can be considered a more lightweight alternative to the CollectionView. However, a significant difference is the lack of Selection, Scrolling, Header, and Footer functionalities in the former.

It is noteworthy that the scrolling support of CollectionView enables the loading of data on-demand.

The scrolling can be facilitated by incorporating the Layout within a ScrollView and configuring the Orientation property to scroll in the desired direction.

The ItemTemplate may also be defined inline. Configure the ItemTemplateSelector property to selectively load the template based on specified conditions.

<HorizontalStackLayout
    BindableLayout.ItemTemplate="{StaticResource OfferTemplate}"
    BindableLayout.ItemsSource="{Binding Offers}">
    <BindableLayout.EmptyView>
        <Label
            Style="{StaticResource Centered}"
            Text="No offers available." />
    </BindableLayout.EmptyView>
</HorizontalStackLayout>

For developers who embrace working with C#, the CommunityToolkit.Maui.Markup package encompasses five Fluent methods for working with the BindableLayout.

The markup methods bear a strong resemblance to the associated property names.

It is noteworthy that the ItemsSource markup method necessitates an IEnumerable collection as its input. If binding support is needed, use the Bind method instead.

Direct Use:

new HorizontalStackLayout().ItemsSource(ViewModel.Offers);

Indirect Use:

new HorizontalStackLayout().Bind(BindableLayout.ItemsSourceProperty, static (ProductViewModel vm) => vm.Offers);

To conclude, the BindableLayout is the most appropriate choice when the dataset is limited and predetermined, and the template is plain and simple. It reduces the memory usage of the page by requiring fewer resources in comparison to the CollectionView.

If you would like to recognize the work, kindly consider sponsoring on the GitHub Sponsor page or Buy Me a Coffee page. Thanks in advance.

Happy coding. Stay connected as we continue to learn and share the experiences from this exciting journey of being a .NET developer.

One reply on “.NET MAUI – BindableLayout”

Comments are closed.