ボタン
.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
は、LineBreakMode
1 行に収まらない場合のテキストの処理方法を決定します。Padding
は、ボタンThickness
のパディングを決定します。Text
は、ボタンstring
の内容として表示されるテキストを定義します。TextColor
は、ボタン Colorのテキストの色を表します。TextTransform
は、ボタンTextTransform
のテキストの大文字と小文字を定義します。
これらのプロパティは、BindableProperty オブジェクトが基になっています。つまり、これらは、データ バインディングの対象にすることができ、スタイルを設定できます。
Note
ButtonプロパティをImageSource定義しますが、このプロパティを使用して画像Buttonを表示できます。このプロパティは、テキストの横Buttonに小さなアイコンを表示するときに使用することを目的としています。
さらに、Buttonイベントを定義しますPressed
Clicked
Released
。 このイベントは 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 するアニメーション関数を呼び出します。
作成する 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 つのプロパティで構成されます。
Command
型ICommand
の場合は、名前空間で定義されているSystem.Windows.Input
インターフェイス。CommandParameter
型Object
のプロパティです。
この方法は、データ バインディングに関連して、特に Model-View-ViewModel (MVVM) パターンを実装する場合に特に適しています。 MVVM アプリケーションでは、ビューモデルはデータ バインディングを使用してオブジェクトにButton接続される型ICommand
のプロパティを定義します。 .NET MAUI では、インターフェイスをCommand
実装し、型ICommand
のプロパティをICommand
定義するビューモデルを支援するクラスも定義されていますCommand<T>
。 コマンドの詳細については、「コマンド実行」を参照してください。
次の例は、名前付きの型double
のプロパティを定義する非常に単純な viewmodel クラスと、名前付きNumber
MultiplyBy2Command
型と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
プロパティが型の Command
2 つのオブジェクトで初期化されます。 コンストラクターには 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 には、 Pressed
VisualState それが有効になっている場合に押されたときに視覚的な変更を 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>
この例では、 Pressed
VisualState 押されると Button 、その Scale
プロパティが既定値の 1 から 0.8 に変更されることを指定します。 通常 Normal
VisualState の状態の場合 Button 、その Scale
プロパティが 1 に設定されることを指定します。 したがって、全体的な効果は、押されると Button 、少し小さいサイズに再スケーリングされ、リリースされると Button 既定のサイズに再スケーリングされることです。
ボタンでビットマップを使用する
このクラスは Button 、 ImageSource 単独で、またはテキストと組み合わせて、小さなビットマップ イメージを Button表示できるプロパティを定義します。 テキストと画像の配置方法を指定することもできます。 プロパティの型ImageSourceはImageSource、ビットマップをファイル、埋め込みリソース、URI、またはストリームから読み込むことができることを意味します。
ビットマップは Button、 ビットマップの大きさに応じて、通常、最適なサイズは 32 ~ 64 のデバイスに依存しない単位です。
のプロパティを使用して、 Text
プロパティの ImageSource 配置方法を ButtonContentLayout
Button指定できます。 このプロパティは型 ButtonContentLayout
であり、コンストラクターには 2 つの引数があります。
- 列挙体の
ImagePosition
メンバー:Left
、、Top
、Right
、または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 を無効にすることができます。
.NET MAUI feedback
フィードバック
フィードバックの送信と表示