Skip to content

MAUI Conventions

Strypper Vandel Jason edited this page Apr 17, 2023 · 5 revisions

Expose event handlers of a ContentView

ℹ️ Overview

Pros 👍🏽

  1. Traditional approach
  2. Easy to understand

Cons 👎🏽

  1. Clunky to setup
  2. Outdated
  3. Tightly coupled

📄Example

XAML

<?xml version="1.0" encoding="utf-8" ?>
<ContentView
    x:Class="PetaverseMAUI.PetProfileCardContentView"
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:app="clr-namespace:PetaverseMAUI"
    xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"
    x:Name="root"
    Padding="10"
    x:DataType="app:PetProfileCardContentView">

    <ContentView.Resources>
        <FontImageSource
            x:Key="GalleryIcon"
            FontFamily="{x:Static app:FontNames.FluentSystemIconsRegular}"
            Glyph="{x:Static app:FluentUIIcon.Ic_fluent_content_view_gallery_28_regular}"
            Color="{x:Static app:AppColors.Black}" />
    </ContentView.Resources>

    <Button Clicked="Detail_Clicked" Text="Detail" />
</ContentView>

CS

    #region [ Delegates ]
    public delegate void PetCardTappedEventHandler(PetProfileCardModel petProfileCardModel);
    #endregion

    #region [ Event Handlers ]
    public event PetCardTappedEventHandler PetCardTapped;

    private void Detail_Clicked(object sender, EventArgs e)
        => PetCardTapped?.Invoke(ComponentData);
    #endregion

Usage

XAML

<DataTemplate x:Key="PetsCollectionViewItemTemplate" x:DataType="app:PetProfileCardModel">
  <app:PetProfileCardContentView ComponentData="{x:Binding}" PetCardTapped="PetProfileCardContentView_PetCardTapped" />
</DataTemplate>

CS

private void PetProfileCardContentView_PetCardTapped(PetProfileCardModel petProfileCardModel){}

Expose command of a ContentView

Publish and Subscribe pattern

Source generator

Observable Properties

Relay Commands