Xamarin.Forms RadioButton

Download Sampleサンプルのダウンロード

Xamarin.FormsRadioButton は、ユーザーがセットから 1 つのオプションを選択できるボタンの一種です。 各選択肢はラジオ ボタンで表され、グループ内のラジオ ボタンは 1 つだけ選択できます。 既定では、各 RadioButton はテキストを表示します。

Screenshot of default RadioButtons

ただし、一部のプラットフォームでは RadioButtonView を表示でき、すべてのプラットフォームで各 RadioButton の外観は ControlTemplate で再定義できます。

Screenshot of redefined RadioButtons

RadioButton コントロールでは、次のプロパティが定義されます。

  • object 型の Content は、RadioButton によって表示される string または View を定義します。
  • bool 型の IsChecked は、RadioButton がチェックされるかどうかを定義します。 このプロパティは TwoWay バインディングを使用し、既定値は false です。
  • string 型の GroupName は、どの RadioButton コントロールが相互に排他的であるかを指定する名前を定義します。 このプロパティの既定値は null です。
  • object 型の Value は、RadioButton に関連付けられた一意の値 (オプション) を定義します。
  • Color 型の BorderColor は、境界線の色を定義します。
  • double 型の BorderWidth は、RadioButton 境界線の幅を定義します。
  • double 型の CharacterSpacing は、表示されるテキストの文字間の間隔を定義します。
  • int 型の CornerRadius は、RadioButton の隅の半径を定義します。
  • FontAttributes 型の FontAttributes は、テキストのスタイルを決定します。
  • string 型の FontFamily は、フォント ファミリを定義します。
  • double 型の FontSize は、フォント サイズを定義します。
  • Color 型の TextColor は、表示されるテキストの色を定義します。
  • TextTransform 型の TextTransform は、表示されるテキストの大文字と小文字を定義します。

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

RadioButton コントロールでは、ユーザーまたはプログラムによる操作によって、IsChecked プロパティが変更されたときに発生する CheckedChanged イベントも定義します。 CheckedChanged イベントに付随する CheckedChangedEventArgs オブジェクトには、bool 型の Value という名前の単一のプロパティがあります。 イベントが発生すると、CheckedChangedEventArgs.Value プロパティの値が IsChecked プロパティの新しい値に設定されます。

RadioButton グループ化は、次の添付プロパティを定義する RadioButtonGroup クラスによって管理できます。

  • string 型の GroupNameLayout<View> 内の RadioButton オブジェクトのグループ名を定義します。
  • object 型のSelectedValueLayout<View> グループ内のチェックされた RadioButton オブジェクトの値を表します。 この添付プロパティは、既定で TwoWay バインディングを使用します。

GroupName 添付プロパティの詳細については、「グループ ラジオボタン」を参照してください。 SelectedValue 添付プロパティの詳細については、「RadioButton の状態変化への応答」を参照してください。

RadioButtons の作成

RadioButton の外観は、RadioButton.Content プロパティに割り当てられたデータの種類によって定義されます。

  • RadioButton.Content プロパティに string が割り当てられると、プロパティは各プラットフォームでラジオ ボタンの円の横に水平に並べて表示されます。
  • RadioButton.ContentView が割り当てられると、サポートされているプラットフォーム (iOS、UWP) に表示されますが、サポートされていないプラットフォームは、View オブジェクトの文字列表現 (Android) にフォールバックします。 いずれの場合も、コンテンツはラジオ ボタンの円の横に水平に並べて表示されます。
  • ControlTemplateRadioButton に適用されると、View をすべてのプラットフォームの RadioButton.Content プロパティに割り当てることができます。 詳細については、「RadioButton の外観を再定義する」をご覧ください。

文字列ベースのコンテンツの表示

RadioButton は、Content プロパティに string が割り当てられると、テキストを表示します。

<StackLayout>
    <Label Text="What's your favorite animal?" />
    <RadioButton Content="Cat" />
    <RadioButton Content="Dog" />
    <RadioButton Content="Elephant" />
    <RadioButton Content="Monkey"
                 IsChecked="true" />
</StackLayout>

この例では、RadioButton オブジェクトは同じ親コンテナー内で暗黙的にグループ化されます。 この XAML により、次のスクリーンショットのような結果になります。

Screenshot of text-based RadioButtons

任意のコンテンツの表示

iOS および UWP では、Content プロパティに View が割り当てられている場合、RadioButton は任意のコンテンツを表示できます。

<StackLayout>
    <Label Text="What's your favorite animal?" />
    <RadioButton>
        <RadioButton.Content>
            <Image Source="cat.png" />
        </RadioButton.Content>
    </RadioButton>
    <RadioButton>
        <RadioButton.Content>
            <Image Source="dog.png" />
        </RadioButton.Content>
    </RadioButton>
    <RadioButton>
        <RadioButton.Content>
            <Image Source="elephant.png" />
        </RadioButton.Content>
    </RadioButton>
    <RadioButton>
        <RadioButton.Content>
            <Image Source="monkey.png" />
        </RadioButton.Content>
    </RadioButton>
</StackLayout>

この例では、RadioButton オブジェクトは同じ親コンテナー内で暗黙的にグループ化されます。 この XAML により、次のスクリーンショットのような結果になります。

Screenshot of view-based RadioButtons

Android では、RadioButton オブジェクトは、コンテンツとして設定されている View オブジェクトの文字列ベースの表現を表示します。

Screenshot of view-based RadioButton on Android

Note

ControlTemplateRadioButton に適用されると、View をすべてのプラットフォームの RadioButton.Content プロパティに割り当てることができます。 詳細については、「RadioButton の外観を再定義する」をご覧ください。

RadioButtons に値を関連付ける

RadioButton オブジェクトには、object 型の Value プロパティがあり、ラジオ ボタンに関連付けるオプションの一意の値を定義します。 これにより、RadioButton の値をコンテンツと異なるものにすることができるため、RadioButton オブジェクトが View オブジェクトを表示する場合に特に便利です。

次の XAML では、各 RadioButton オブジェクトで Content プロパティと Value プロパティを設定する方法を示します。

<StackLayout>
    <Label Text="What's your favorite animal?" />
    <RadioButton Value="Cat">
        <RadioButton.Content>
            <Image Source="cat.png" />
        </RadioButton.Content>
    </RadioButton>
    <RadioButton Value="Dog">
        <RadioButton.Content>
            <Image Source="dog.png" />
        </RadioButton.Content>
    </RadioButton>
    <RadioButton Value="Elephant">
        <RadioButton.Content>
            <Image Source="elephant.png" />
        </RadioButton.Content>
    </RadioButton>
    <RadioButton Value="Monkey">
        <RadioButton.Content>
            <Image Source="monkey.png" />
        </RadioButton.Content>
    </RadioButton>
</StackLayout>

この例では、各 RadioButton がコンテンツとして Image を持っており、文字列ベースの値も定義します。 これにより、チェックされたラジオ ボタンの値を簡単に識別できます。

グループ RadioButtons

ラジオ ボタンはグループで機能し、ラジオ ボタンをグループ化するには 3 つの方法があります。

  • 同じ親コンテナー内に追加します。 これは "暗黙的な" グループ化と呼ばれます。
  • 各ラジオ ボタンの GroupName プロパティを同じ値に設定します。 これは "明示的な" グループ化と呼ばれます。
  • 親コンテナーに RadioButtonGroup.GroupName 添付プロパティを設定すると、コンテナー内の RadioButton オブジェクトの GroupName プロパティが設定されます。 これは "明示的な" グループ化とも呼ばれます。

重要

RadioButton オブジェクトは、グループ化するために同じ親に属している必要はありません。 グループ名を共有する場合は、相互に排他的です。

GroupName プロパティを使用した明示的なグループ化

次の XAML の例は、GroupName プロパティを設定して RadioButton オブジェクトを明示的にグループ化する方法を示します。

<Label Text="What's your favorite color?" />
<RadioButton Content="Red"
             GroupName="colors" />
<RadioButton Content="Green"
             GroupName="colors" />
<RadioButton Content="Blue"
             GroupName="colors" />
<RadioButton Content="Other"
             GroupName="colors" />

この例では、各 RadioButton が同じ GroupName 値を共有するため、相互に排他的です。

RadioButtonGroup.GroupName 添付プロパティを使用した明示的なグループ化

RadioButtonGroup クラスは、string 型の GroupName 添付プロパティを定義し、Layout<View> オブジェクトに設定できます。 これにより、任意のレイアウトをラジオ ボタン グループに変換できます。

<StackLayout RadioButtonGroup.GroupName="colors">
    <Label Text="What's your favorite color?" />
    <RadioButton Content="Red" />
    <RadioButton Content="Green" />
    <RadioButton Content="Blue" />
    <RadioButton Content="Other" />
</StackLayout>

この例では、StackLayout 内の各 RadioButtonGroupName プロパティは colors に設定され、相互に排他的になります。

Note

RadioButtonGroup.GroupName 添付プロパティを設定する Layout<View> オブジェクトに、GroupName プロパティを設定する RadioButton が含まれている場合、RadioButton.GroupName プロパティの値が優先されます。

RadioButton 状態の変更に対応する

ラジオ ボタンには、チェックされているかチェックが解除されているかの 2 つの状態があります。 ラジオ ボタンがチェックされている場合、その IsChecked プロパティは true になります。 ラジオ ボタンのチェックが解除されると、その IsChecked プロパティは false になります。 ラジオ ボタンは、同じグループ内の別のラジオ ボタンをクリックするとチェックを解除できますが、もう一度クリックしてもチェックを解除することはできません。 ただし、プログラムで IsChecked プロパティを false に設定すると、ラジオ ボタンをオフにすることができます。

イベントの発生に対応する

IsChecked プロパティがユーザーによる操作またはプログラムによる操作によって変更された場合、CheckedChanged イベントが発生します。 このイベントのイベント ハンドラーを登録して、変更に応答できます。

<RadioButton Content="Red"
             GroupName="colors"
             CheckedChanged="OnColorsRadioButtonCheckedChanged" />

分離コードには、CheckedChanged イベントのハンドラーが含まれます。

void OnColorsRadioButtonCheckedChanged(object sender, CheckedChangedEventArgs e)
{
    // Perform required operation
}

引数 sender は、このイベントに責任を持つ RadioButton です。 これを使用して、RadioButton オブジェクトにアクセスしたり、同じ CheckedChanged イベント ハンドラーを共有する複数の RadioButton オブジェクトを区別したりできます。

プロパティの変更に対応する

RadioButtonGroup クラスは、object 型の SelectedValue 添付プロパティを定義し、Layout<View> オブジェクトに設定できます。 この添付プロパティは、レイアウトで定義されたグループ内のチェックされた RadioButton の値を表します。

ユーザーによる操作またはプログラムによる操作によって IsChecked プロパティが変更されると、RadioButtonGroup.SelectedValue 添付プロパティも変更されます。 したがって、RadioButtonGroup.SelectedValue 添付プロパティは、ユーザーの選択を格納するプロパティにデータ バインドできます。

<StackLayout RadioButtonGroup.GroupName="{Binding GroupName}"
             RadioButtonGroup.SelectedValue="{Binding Selection}">
    <Label Text="What's your favorite animal?" />
    <RadioButton Content="Cat"
                 Value="Cat" />
    <RadioButton Content="Dog"
                 Value="Dog" />
    <RadioButton Content="Elephant"
                 Value="Elephant" />
    <RadioButton Content="Monkey"
                 Value="Monkey"/>
    <Label x:Name="animalLabel">
        <Label.FormattedText>
            <FormattedString>
                <Span Text="You have chosen:" />
                <Span Text="{Binding Selection}" />
            </FormattedString>
        </Label.FormattedText>
    </Label>
</StackLayout>

この例では、RadioButtonGroup.GroupName 添付プロパティの値は、バインディング コンテキストの GroupName プロパティによって設定されます。 同様に、RadioButtonGroup.SelectedValue 添付プロパティの値は、バインディング コンテキストの Selection プロパティによって設定されます。 さらに、Selection プロパティはチェックされた RadioButtonValue プロパティに更新されます。

RadioButton の表示状態

RadioButton オブジェクトには CheckedUnchecked の表示状態があり、RadioButton がオンまたはオフになったときに視覚的な変化を開始するために使用できます。

次の XAML 例は、CheckedUnchecked の状態の視覚的な状態を定義する方法を示しています。

<ContentPage ...>
    <ContentPage.Resources>
        <Style TargetType="RadioButton">
            <Setter Property="VisualStateManager.VisualStateGroups">
                <VisualStateGroupList>
                    <VisualStateGroup x:Name="CheckedStates">
                        <VisualState x:Name="Checked">
                            <VisualState.Setters>
                                <Setter Property="TextColor"
                                        Value="Green" />
                                <Setter Property="Opacity"
                                        Value="1" />
                            </VisualState.Setters>
                        </VisualState>
                        <VisualState x:Name="Unchecked">
                            <VisualState.Setters>
                                <Setter Property="TextColor"
                                        Value="Red" />
                                <Setter Property="Opacity"
                                        Value="0.5" />
                            </VisualState.Setters>
                        </VisualState>
                    </VisualStateGroup>
                </VisualStateGroupList>
            </Setter>
        </Style>
    </ContentPage.Resources>
    <StackLayout>
        <Label Text="What's your favorite mode of transport?" />
        <RadioButton Content="Car" />
        <RadioButton Content="Bike" />
        <RadioButton Content="Train" />
        <RadioButton Content="Walking" />
    </StackLayout>
</ContentPage>

この例では、暗黙的な Style によって RadioButton オブジェクトがターゲットにされています。 CheckedVisualState は、RadioButton がチェックされている場合、その TextColor プロパティが Opacity の値 1 で緑色に設定されることを指定します。 UncheckedVisualState は、RadioButton がチェックされていない場合、その TextColor プロパティが Opacity の値 0.5 で赤に設定されることを指定します。 そのため、RadioButton がチェックされていない場合、全体的な効果は赤で部分的に透明になり、チェックされている場合は透明性のない緑色になります。

Screenshot of RadioButton visual states

ビジュアルの状態の詳細については、「Xamarin.Forms Visual State Manager」をご覧ください。

RadioButton の外観の再定義

既定では、RadioButton オブジェクトはプラットフォーム レンダラーを使用して、サポートされているプラットフォームでネイティブ コントロールを利用します。 ただし、RadioButton の視覚構造は ControlTemplate を使用して再定義できるため、RadioButton オブジェクトはすべてのプラットフォームで同じ外観になります。 これは、RadioButton クラスが TemplatedView クラスから継承しているために可能になります。

次の XAML は、RadioButton オブジェクトの視覚構造を再定義するために使用できる ControlTemplate を示しています。

<ContentPage ...>
    <ContentPage.Resources>
        <ControlTemplate x:Key="RadioButtonTemplate">
            <Frame BorderColor="#F3F2F1"
                   BackgroundColor="#F3F2F1"
                   HasShadow="False"
                   HeightRequest="100"
                   WidthRequest="100"
                   HorizontalOptions="Start"
                   VerticalOptions="Start"
                   Padding="0">
                <VisualStateManager.VisualStateGroups>
                    <VisualStateGroupList>
                        <VisualStateGroup x:Name="CheckedStates">
                            <VisualState x:Name="Checked">
                                <VisualState.Setters>
                                    <Setter Property="BorderColor"
                                            Value="#FF3300" />
                                    <Setter TargetName="check"
                                            Property="Opacity"
                                            Value="1" />
                                </VisualState.Setters>
                            </VisualState>
                            <VisualState x:Name="Unchecked">
                                <VisualState.Setters>
                                    <Setter Property="BackgroundColor"
                                            Value="#F3F2F1" />
                                    <Setter Property="BorderColor"
                                            Value="#F3F2F1" />
                                    <Setter TargetName="check"
                                            Property="Opacity"
                                            Value="0" />
                                </VisualState.Setters>
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateGroupList>
                </VisualStateManager.VisualStateGroups>
                <Grid Margin="4"
                      WidthRequest="100">
                    <Grid WidthRequest="18"
                          HeightRequest="18"
                          HorizontalOptions="End"
                          VerticalOptions="Start">
                        <Ellipse Stroke="Blue"
                                 Fill="White"
                                 WidthRequest="16"
                                 HeightRequest="16"
                                 HorizontalOptions="Center"
                                 VerticalOptions="Center" />
                        <Ellipse x:Name="check"
                                 Fill="Blue"
                                 WidthRequest="8"
                                 HeightRequest="8"
                                 HorizontalOptions="Center"
                                 VerticalOptions="Center" />
                    </Grid>
                    <ContentPresenter />
                </Grid>
            </Frame>
        </ControlTemplate>

        <Style TargetType="RadioButton">
            <Setter Property="ControlTemplate"
                    Value="{StaticResource RadioButtonTemplate}" />
        </Style>
    </ContentPage.Resources>
    <!-- Page content -->
</ContentPage>

この例では、ControlTemplate のルート要素は、CheckedUnchecked の表示状態を定義する Frame オブジェクトです。 Frame オブジェクトは、GridEllipse、および ContentPresenter オブジェクトの組み合わせを使用して、RadioButton の視覚的な構造を定義します。 この例には、RadioButtonTemplate をページ上の RadioButton オブジェクトの ControlTemplate プロパティに割り当てる暗黙的なスタイルも含まれています。

Note

ContentPresenter オブジェクトは、RadioButton コンテンツが表示される視覚構造内の位置をマークします。

次の XAML は、暗黙的なスタイルを介して ControlTemplate を使用する RadioButton オブジェクトを示しています。

<StackLayout>
    <Label Text="What's your favorite animal?" />
    <StackLayout RadioButtonGroup.GroupName="animals"
                 Orientation="Horizontal">
        <RadioButton Value="Cat">
            <RadioButton.Content>
                <StackLayout>
                    <Image Source="cat.png"
                           HorizontalOptions="Center"
                           VerticalOptions="CenterAndExpand" />
                    <Label Text="Cat"
                           HorizontalOptions="Center"
                           VerticalOptions="End" />
                </StackLayout>
            </RadioButton.Content>
        </RadioButton>
        <RadioButton Value="Dog">
            <RadioButton.Content>
                <StackLayout>
                    <Image Source="dog.png"
                           HorizontalOptions="Center"
                           VerticalOptions="CenterAndExpand" />
                    <Label Text="Dog"
                           HorizontalOptions="Center"
                           VerticalOptions="End" />
                </StackLayout>
            </RadioButton.Content>
        </RadioButton>
        <RadioButton Value="Elephant">
            <RadioButton.Content>
                <StackLayout>
                    <Image Source="elephant.png"
                           HorizontalOptions="Center"
                           VerticalOptions="CenterAndExpand" />
                    <Label Text="Elephant"
                           HorizontalOptions="Center"
                           VerticalOptions="End" />
                </StackLayout>
            </RadioButton.Content>
        </RadioButton>
        <RadioButton Value="Monkey">
            <RadioButton.Content>
                <StackLayout>
                    <Image Source="monkey.png"
                           HorizontalOptions="Center"
                           VerticalOptions="CenterAndExpand" />
                    <Label Text="Monkey"
                           HorizontalOptions="Center"
                           VerticalOptions="End" />
                </StackLayout>
            </RadioButton.Content>
        </RadioButton>
    </StackLayout>
</StackLayout>

この例では、各 RadioButton に定義されたビジュアル構造が ControlTemplate で定義されたビジュアル構造に置き換えられるため、実行時に ControlTemplate 内のオブジェクトが各 RadioButton のビジュアル ツリーの一部になります。 さらに、各 RadioButton のコンテンツは、コントロール テンプレートで定義された ContentPresenter に置き換えられます。 その結果、次の RadioButton のような外観になります。

Screenshot of templated RadioButtons

コントロール テンプレートの詳細については、「Xamarin.Forms のコントロール テンプレート」を参照してください。

RadioButton の無効化

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