ボタン

.NET マルチプラットフォーム アプリ UI (.NET MAUI) Button は、テキストを表示し、タップまたはクリックに応答して、タスクを実行するようにアプリに指示します。 通常、 Button コマンドを示す短いテキスト文字列が表示されますが、ビットマップイメージやテキストと画像の組み合わせを表示することもできます。 Button指で押すか、マウスでクリックすると、そのコマンドが開始されます。

Button は次の特性を定義します。

  • BorderColorは、ボタン Colorの境界線の色を表します。
  • BorderWidthは、ボタン doubleの境界線の幅を定義します。
  • CharacterSpacingは、ボタン doubleのテキストの文字間の間隔を定義します。
  • Commandの型 ICommandは、ボタンがタップされたときに実行されるコマンドを定義します。
  • CommandParameterの型 objectは、渡される Commandパラメーターです。
  • ContentLayoutの型 ButtonContentLayoutは、ボタンイメージの位置とボタンの画像とテキストの間隔を制御するオブジェクトを定義します。
  • CornerRadiusの種類 intは、ボタンの境界線の角の半径を表します。
  • FontAttributesは、テキスト FontAttributesスタイルを決定します。
  • FontAutoScalingEnabledは、オペレーティング boolシステムで設定されたスケーリング設定をボタン テキストに反映するかどうかを定義します。 このプロパティの既定値は true です。
  • FontFamilyは、フォント stringファミリを定義します。
  • FontSizeは、フォント doubleサイズを定義します。
  • ImageSourceは、ボタン ImageSourceの内容として表示するビットマップ イメージを指定します。
  • LineBreakModeは、 LineBreakMode1 行に収まらない場合のテキストの処理方法を決定します。
  • Paddingは、ボタン Thicknessのパディングを決定します。
  • Textは、ボタン stringの内容として表示されるテキストを定義します。
  • TextColorは、ボタン Colorのテキストの色を表します。
  • TextTransformは、ボタン TextTransformのテキストの大文字と小文字を定義します。

これらのプロパティは、BindableProperty オブジェクトが基になっています。つまり、これらは、データ バインディングの対象にすることができ、スタイルを設定できます。

Note

ButtonプロパティをImageSource定義しますが、このプロパティを使用して画像Buttonを表示できます。このプロパティは、テキストの横Buttonに小さなアイコンを表示するときに使用することを目的としています。

さらに、Buttonイベントを定義しますPressedClickedReleased。 このイベントは Clicked 、指またはマウス ポインターを使ったタップがボタンの表面から離されると Button 発生します。 イベントは Pressed 、指が上を押 Buttonすか、マウス ボタンがポインターの上 Buttonに置かれたときに発生します。 このイベントは Released 、指またはマウス ボタンが離されると発生します。 一般に Clicked 、イベントもイベントと Released 同時に発生しますが、指またはマウス ポインターが解放される前の Button サーフェスから離れてスライドすると、 Clicked イベントが発生しない可能性があります。

重要

タップ Button に応答するには、その IsEnabled プロパティが true 設定されている必要があります。

ボタンを作成する

ボタンを作成するには、オブジェクトを Button 作成し、そのイベントを Clicked 処理します。

次の XAML の例は、次のように作成する方法を Button示しています。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ButtonDemos.BasicButtonClickPage"
             Title="Basic Button Click">
    <StackLayout>
        <Button Text="Click to Rotate Text!"
                VerticalOptions="Center"
                HorizontalOptions="Center"
                Clicked="OnButtonClicked" />
        <Label x:Name="label"
               Text="Click the Button above"
               FontSize="18"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
    </StackLayout>
</ContentPage>

Text プロパティでは、Button に表示するテキストを指定します。 イベントは Clicked 、という名前 OnButtonClickedのイベント ハンドラーに設定されます。 このハンドラーは、分離コード ファイルにあります。

public partial class BasicButtonClickPage : ContentPage
{
    public BasicButtonClickPage ()
    {
        InitializeComponent ();
    }

    async void OnButtonClicked(object sender, EventArgs args)
    {
        await label.RelRotateTo(360, 1000);
    }
}

この例では、タップされると Button 、メソッドが OnButtonClicked 実行されます。 引数は sender 、このイベントを Button 担当するオブジェクトです。 これを使用して、オブジェクトにButtonアクセスしたり、同じClickedイベントを共有する複数Buttonのオブジェクトを区別したりできます。 ハンドラーは Clicked 、1000 ミリ秒で 360 度回転 Label するアニメーション関数を呼び出します。

Screenshot of a Button.

作成する Button 同等の C# コードは次のとおりです。

Button button = new Button
{
    Text = "Click to Rotate Text!",
    VerticalOptions = LayoutOptions.Center,
    HorizontalOptions = LayoutOptions.Center
};
button.Clicked += async (sender, args) => await label.RelRotateTo(360, 1000);

コマンド インターフェイスを使用する

アプリは、イベントを処理せずにタップにButtonClicked応答できます。 コマンドButtonまたはコマンド 実行インターフェイスと呼ばれる別の通知メカニズムを実装します。 これは、次の 2 つのプロパティで構成されます。

  • CommandICommandの場合は、名前空間で定義されている System.Windows.Input インターフェイス。
  • CommandParameterObjectのプロパティです。

この方法は、データ バインディングに関連して、特に Model-View-ViewModel (MVVM) パターンを実装する場合に特に適しています。 MVVM アプリケーションでは、ビューモデルはデータ バインディングを使用してオブジェクトにButton接続される型ICommandのプロパティを定義します。 .NET MAUI では、インターフェイスをCommand実装し、型ICommandのプロパティをICommand定義するビューモデルを支援するクラスも定義されていますCommand<T>。 コマンドの詳細については、「コマンド実行」を参照してください

次の例は、名前付きの型doubleのプロパティを定義する非常に単純な viewmodel クラスと、名前付きNumberMultiplyBy2Command型とDivideBy2Command型の ICommand 2 つのプロパティを示しています。

public class CommandDemoViewModel : INotifyPropertyChanged
{
    double number = 1;

    public event PropertyChangedEventHandler PropertyChanged;

    public ICommand MultiplyBy2Command { get; private set; }
    public ICommand DivideBy2Command { get; private set; }

    public CommandDemoViewModel()
    {
        MultiplyBy2Command = new Command(() => Number *= 2);
        DivideBy2Command = new Command(() => Number /= 2);
    }

    public double Number
    {
        get
        {
            return number;
        }
        set
        {
            if (number != value)
            {
                number = value;
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Number"));
            }
        }
    }
}

この例では、クラスのコンストラクターで 2 つの ICommand プロパティが型の Command2 つのオブジェクトで初期化されます。 コンストラクターには Command 、プロパティの値を 2 倍または半分にする小さな関数 (コンストラクター引数と呼ばれます execute ) が Number 含まれます。

次の XAML の例では、クラスを CommandDemoViewModel 使用します。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ButtonDemos"
             x:Class="ButtonDemos.BasicButtonCommandPage"
             Title="Basic Button Command">
    <ContentPage.BindingContext>
        <local:CommandDemoViewModel />
    </ContentPage.BindingContext>

    <StackLayout>
        <Label Text="{Binding Number, StringFormat='Value is now {0}'}"
               FontSize="18"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
        <Button Text="Multiply by 2"
                VerticalOptions="Center"
                HorizontalOptions="Center"
                Command="{Binding MultiplyBy2Command}" />
        <Button Text="Divide by 2"
                VerticalOptions="Center"
                HorizontalOptions="Center"
                Command="{Binding DivideBy2Command}" />
    </StackLayout>
</ContentPage>

この例では、 Label 要素と 2 つの Button オブジェクトに、クラスの 3 つのプロパティへのバインドが CommandDemoViewModel 含まれています。 2 つの Button オブジェクトがタップされると、コマンドが実行され、数値が変更されます。 ハンドラーよりも Clicked このアプローチの利点は、このページの機能を含むすべてのロジックが分離コード ファイルではなくビューモデルに配置され、ビジネス ロジックからユーザー インターフェイスをより適切に分離できる点です。

また、オブジェクトでオブジェクトの Command 有効化と無効化を Button 制御することもできます。 たとえば、数値の範囲を 2 10 から 2~ 10 の範囲に制限するとします。 有効にする必要がある場合に返すtrue別の関数をコンストラクター (引数と呼ばれますcanExecute) にButton追加できます。

public class CommandDemoViewModel : INotifyPropertyChanged
{
    ···
    public CommandDemoViewModel()
    {
        MultiplyBy2Command = new Command(
            execute: () =>
            {
                Number *= 2;
                ((Command)MultiplyBy2Command).ChangeCanExecute();
                ((Command)DivideBy2Command).ChangeCanExecute();
            },
            canExecute: () => Number < Math.Pow(2, 10));

        DivideBy2Command = new Command(
            execute: () =>
            {
                Number /= 2;
                ((Command)MultiplyBy2Command).ChangeCanExecute();
                ((Command)DivideBy2Command).ChangeCanExecute();
            },
            canExecute: () => Number > Math.Pow(2, -10));
    }
    ···
}

この例では、メソッドを呼び出して ChangeCanExecute 無効 Command にするかどうかを判断できるように Command 、メソッドの呼び出 canExecute しが Button 必要です。 このコードが変更されると、数値が制限に達すると、無効 Button になります。

2 つ以上 Button の要素を同じ ICommand プロパティにバインドすることもできます。 要素はButton、次のButtonプロパティをCommandParameter使用して区別できます。 この場合は、ジェネリック Command<T> クラスを使用します。 CommandParameterその後、オブジェクトは引数として and canExecute メソッドにexecute渡されます。 詳細については、「コマンド実行」を参照してください

ボタンを押して離す

イベントは Pressed 、指が上を押 Buttonすか、マウス ボタンがポインターの上 Buttonに置かれたときに発生します。 このイベントは Released 、指またはマウス ボタンが離されると発生します。 一般に Clicked 、イベントもイベントと Released 同時に発生しますが、指またはマウス ポインターが解放される前の Button サーフェスから離れてスライドすると、 Clicked イベントが発生しない可能性があります。

次の XAML の例は、LabelイベントにアタッチされたハンドラーとButtonReleasedハンドラーをPressed示しています。

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="ButtonDemos.PressAndReleaseButtonPage"
             Title="Press and Release Button">
    <StackLayout>
        <Button Text="Press to Rotate Text!"
                VerticalOptions="Center"
                HorizontalOptions="Center"
                Pressed="OnButtonPressed"
                Released="OnButtonReleased" />
        <Label x:Name="label"
               Text="Press and hold the Button above"
               FontSize="18"
               VerticalOptions="Center"
               HorizontalOptions="Center" />
    </StackLayout>
</ContentPage>

分離コード ファイルは、イベントが発生したときにPressedアニメーション化Labelされますが、イベントが発生したときにローテーションをReleased中断します。

public partial class PressAndReleaseButtonPage : ContentPage
{
    IDispatcherTimer timer;
    Stopwatch stopwatch = new Stopwatch();

    public PressAndReleaseButtonPage()
    {
        InitializeComponent();

        timer = Dispatcher.CreateTimer();
        timer.Interval = TimeSpan.FromMilliseconds(16);
        timer.Tick += (s, e) =>
        {
            label.Rotation = 360 * (stopwatch.Elapsed.TotalSeconds % 1);
        };
    }

    void OnButtonPressed(object sender, EventArgs args)
    {
        stopwatch.Start();
        timer.Start();
    }

    void OnButtonReleased(object sender, EventArgs args)
    {
        stopwatch.Stop();
        timer.Stop();
    }
}

その結果、指が Label 接触 Buttonしている間だけ回転し、指が離されると停止します。

ボタンの表示状態

Button には、 PressedVisualState それが有効になっている場合に押されたときに視覚的な変更を Button 開始するために使用できるaがあります。

次の XAML の例は、状態の表示状態を定義する方法を Pressed 示しています。

<Button Text="Click me!"
        ...>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup x:Name="CommonStates">
            <VisualState x:Name="Normal">
                <VisualState.Setters>
                    <Setter Property="Scale"
                            Value="1" />
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="Pressed">
                <VisualState.Setters>
                    <Setter Property="Scale"
                            Value="0.8" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
</Button>

この例では、 PressedVisualState 押されると Button 、その Scale プロパティが既定値の 1 から 0.8 に変更されることを指定します。 通常 NormalVisualState の状態の場合 Button 、その Scale プロパティが 1 に設定されることを指定します。 したがって、全体的な効果は、押されると Button 、少し小さいサイズに再スケーリングされ、リリースされると Button 既定のサイズに再スケーリングされることです。

表示状態の詳細については、「表示状態」を参照してください

ボタンでビットマップを使用する

このクラスは ButtonImageSource 単独で、またはテキストと組み合わせて、小さなビットマップ イメージを Button表示できるプロパティを定義します。 テキストと画像の配置方法を指定することもできます。 プロパティの型ImageSourceImageSource、ビットマップをファイル、埋め込みリソース、URI、またはストリームから読み込むことができることを意味します。

ビットマップは Button、 ビットマップの大きさに応じて、通常、最適なサイズは 32 ~ 64 のデバイスに依存しない単位です。

のプロパティを使用して、 Text プロパティの ImageSource 配置方法を ButtonContentLayoutButton指定できます。 このプロパティは型 ButtonContentLayoutであり、コンストラクターには 2 つの引数があります。

  • 列挙体の ImagePosition メンバー: Left、、 TopRight、または Bottom テキストに対するビットマップの相対表示方法を示します。
  • doubleビットマップとテキストの間の間隔の値。

XAML では、列挙メンバーのみ、またはスペース、またはその両方をコンマで区切って任意の順序で指定することで、プロパティを作成 Button および設定 ContentLayout できます。

<Button Text="Button text"
        ImageSource="button.png"
        ContentLayout="Right, 20" />

同等の C# コードを次に示します。

Button button = new Button
{
    Text = "Button text",
    ImageSource = new FileImageSource
    {
        File = "button.png"
    },
    ContentLayout = new Button.ButtonContentLayout(Button.ButtonContentLayout.ImagePosition.Right, 20)
};

ボタンを無効にする

アプリがクリックが Button 有効な操作ではない状態になる場合があります。 このような場合は、その IsEnabled プロパティを false に設定することで、Button を無効にすることができます。