本記事の概要
RadioButton には、表面に表示するテキスト以外に任意の値を持つことができます。
この記事では RadioButton で値を設定する方法と値を取得する方法について説明します。
公式サイト情報はコチラを参照してください。
RadioButton ごとに任意の値を設定する
RadioButton は 表面に表示するテキストとは別に、value プロパティを使用して個々に任意の値を設定することができます。
以下の例では、年代の選択肢「20代」「30代」「40代」の RadioButton があり、それぞれのValue プロパティに「20」「30」「40」の値を持たせる例です。
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>せ
選択された RadioButton の値(Value)を取得する
以下の例では、選択された RadioButton の値(Value プロパティ)を取得してラベルに表示する例です。
先ほどの XAML では、それぞれの RadioButton のチェック状態が変更されると RadioButton_CheckedChanged が応答します。
このイベントが発生した時は、Value プロパティを参照してチェック状態が変更された RadioButton の Value プロパティの値を表示しています。
C# の例
private void RadioButton_CheckedChanged(object sender, CheckedChangedEventArgs e) { myLabel.Text = ((RadioButton)sender).Value.ToString(); }
.NET MAUI Tips
本サイトでまとめている .NET MAUI Tips の一覧はこちらから確認できます。
Please follow and like us:
コメント