MAUIのXAMLでボタンの中身をViewにしたい

提供: MonoBook
ナビゲーションに移動 検索に移動


MAUIのButtonの中身をXAMLの図形機能でベクター画像として描画しようと思ったがMAUIのButtonの中に別Viewは配置できないらしい。 MAUIのButtonクラスはViewの派生クラスでありダイレクトコンテンツをサポートしていないらしい。 Buttonクラスは文字を表示するしかできない。 まじでゴミ。

Gridなどで代用しようと試みたがGridにはClickedなどのイベントも見当たらない。 まじでゴミ。

解決策:ContentView派生クラスのボタンを作る[編集 | ソースを編集]

ViewではなくContentViewを基底クラスとするボタンを作る。

using System;
using Microsoft.Maui.Controls;

public class ContentButton : ContentView
{
    public event EventHandler? Clicked;

    public ContentButton()
    {
        var tapGestureRecognizer = new TapGestureRecognizer();
        tapGestureRecognizer.Tapped += (s, e) => Clicked?.Invoke(this, e);
        GestureRecognizers.Add(tapGestureRecognizer);
    }
}

こんな感じで使う。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="using:Capture8"
             x:Class="Capture8.MainPage">
    <StackLayout>

        <!-- スマホのカメラによくある撮影ボタンのようなもの -->
        <local:ContentButton
            BackgroundColor="CornflowerBlue"
            WidthRequest="80"
            HeightRequest="80"
            HorizontalOptions="CenterAndExpand"
            VerticalOptions="CenterAndExpand"
            Clicked="OnCaptureButtonClicked" >
            <Grid>
                <Ellipse WidthRequest="70" HeightRequest="70" Fill="Red" />
                <Ellipse WidthRequest="60" HeightRequest="60" Fill="White" />
            </Grid>
        </local:ContentButton>

    </StackLayout>          
</ContentPage>