本記事の概要
この記事では RadioButton のチェック状態の変更に対応する方法について説明します。
公式サイト情報はコチラを参照してください。
チェック状態の変更を受け取るイベント
RadioButton はチェック状態が変更されると CheckedChanged イベントが発生します。
以下に CheckedChanged イベントの基本使用例を示します。
この例では年代の選択肢「20代」「30代」「40代」の RadioButton があり、30代の RadioButton にのみ CheckedChanged イベントを設定しています。
30代がチェックされるとラベルに「30代」と表示します。
XAML の例
<?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" x:Class="MauiAppSample.MainPage"> <ScrollView> <VerticalStackLayout Spacing="25" Padding="30,0" VerticalOptions="CenterAndExpand"> <StackLayout RadioButtonGroup.GroupName="Generation"> <Label Text="年代" /> <RadioButton Content="20代" Value="20"/> <RadioButton Content="30代" Value="30" CheckedChanged="RadioButton_CheckedChanged"/> <RadioButton Content="40代" Value="40"/> </StackLayout> <Label x:Name="myLabel" /> </VerticalStackLayout> </ScrollView> </ContentPage>
C# の例
private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e) { myLabel.Text = String.IsNullOrEmpty(myLabel.Text) ? "30代" : ""; }
イベントを共有してチェック状態に応答する
CheckedChanged イベントは、複数の RadioButton で共有することができます。
ですので、以下の例のように、全ての RadioButton で同じ CheckedChanged イベントを使用することができます。
CheckedChanged イベントの引数には、チェック状態が変更された RadioButton の情報が入っています。((RadioButton)sender).プロパティ名 のようにすることで、チェック状態が変更された RadioButton のプロパティを参照することができます。
この例では、Content プロパティを参照して、チェック状態が変更された RadioButton の表示テキストを取得してラベルに表示しています。
XAML の例
<?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" x:Class="MauiAppSample.MainPage"> <ScrollView> <VerticalStackLayout Spacing="25" Padding="30,0" VerticalOptions="CenterAndExpand"> <StackLayout RadioButtonGroup.GroupName="Generation"> <Label Text="性別" /> <RadioButton Content="20代" Value="20" CheckedChanged="RadioButton_CheckedChanged"/> <RadioButton Content="30代" Value="30" CheckedChanged="RadioButton_CheckedChanged"/> <RadioButton Content="40代" Value="40" CheckedChanged="RadioButton_CheckedChanged"/> </StackLayout> <Label x:Name="myLabel" /> </VerticalStackLayout> </ScrollView> </ContentPage>
C# の例
private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e) { myLabel.Text = ((RadioButton)sender).Content.ToString(); }
.NET MAUI Tips
本サイトでまとめている .NET MAUI Tips の一覧はこちらから確認できます。
Please follow and like us:
コメント