Xamarin.Forms Radiobutton

Download Sample 샘플 다운로드

이 Xamarin.FormsRadioButton 단추는 사용자가 집합에서 하나의 옵션을 선택할 수 있도록 하는 단추의 유형입니다. 각 옵션은 하나의 라디오 단추로 표시되며 그룹에서 하나의 라디오 단추만 선택할 수 있습니다. 기본적으로 각 RadioButton 텍스트는 다음과 같이 표시됩니다.

Screenshot of default RadioButtons

그러나 일부 플랫폼에서는 RadioButtonView다음을 사용하여 각 RadioButton 플랫폼의 모양을 다시 정의 ControlTemplate할 수 있습니다.

Screenshot of redefined RadioButtons

컨트롤은 RadioButton 다음 속성을 정의합니다.

  • Content에 의해 표시될 형식 Viewobjectstring 입니다RadioButton.
  • IsChecked가 검사 여부를 정의하는 형식boolRadioButton 입니다. 이 속성은 바인딩을 TwoWay 사용하며 기본값은 .입니다 false.
  • GroupName는 상호 배타적인 컨트롤을 지정 RadioButton 하는 이름을 정의하는 형식string의 입니다. 이 속성의 기본값 null은 .
  • Value에 연결된 선택적 고유 값을 정의하는 형식 object의 입니다 RadioButton.
  • BorderColor테두리 스트로크 색을 정의하는 형식 Color의 입니다.
  • BorderWidth테두리의 너비를 정의하는 형식 double의 입니다 RadioButton .
  • CharacterSpacing표시된 텍스트의 문자 사이의 간격을 정의하는 형식 double의 입니다.
  • CornerRadius의 모퉁이 반경을 정의하는 형식 int의 입니다 RadioButton.
  • FontAttributes텍스트 스타일을 결정하는 형식 FontAttributes의 입니다.
  • FontFamily- 글꼴 패밀리를 정의하는 형식 string입니다.
  • FontSize글꼴 크기를 정의하는 형식 double의 입니다.
  • TextColor표시된 텍스트의 색을 정의하는 형식 Color의 입니다.
  • TextTransform표시된 텍스트의 대/소문자를 정의하는 형식 TextTransform의 입니다.

이러한 속성은 BindableProperty 개체에서 지원하며, 따라서 데이터 바인딩의 대상이 될 수 있고 스타일이 지정될 수 있습니다.

또한 컨트롤은 RadioButton 사용자 또는 프로그래밍 방식 조작을 통해 속성이 IsChecked 변경되면 발생하는 이벤트를 정의 CheckedChanged 합니다. CheckedChangedEventArgs 이벤트와 함께 CheckedChanged 제공되는 개체에는 형식bool의 단일 속성이 있습니다Value. 이벤트가 발생하면 속성 값 CheckedChangedEventArgs.Value 이 속성의 IsChecked 새 값으로 설정됩니다.

RadioButton 그룹화는 다음 연결된 속성을 정의하는 클래스에서 관리할 RadioButtonGroup 수 있습니다.

  • GroupName에 있는 개체의 그룹 이름을 정의하는 형식string의 입니다Layout<View>.RadioButton
  • SelectedValue그룹 내에서 검사 개체의 값을 나타내는 형식objectRadioButton입니다Layout<View>. 이 연결된 속성은 기본적으로 바인딩을 TwoWay 사용합니다.

연결된 속성에 GroupName 대한 자세한 내용은 Group RadioButtons를 참조 하세요. 연결된 속성에 SelectedValue 대한 자세한 내용은 RadioButton 상태 변경에 응답(Respond to RadioButton) 상태를 참조 하세요.

RadioButtons 만들기

모양 RadioButton 은 속성에 할당된 데이터 형식에 RadioButton.Content 의해 정의됩니다.

  • 속성이 RadioButton.Content 할당 string되면 각 플랫폼에 표시되고 라디오 단추 원 옆에 가로로 정렬됩니다.
  • RadioButton.Content 할당View되면 지원되는 플랫폼(iOS, UWP)에 표시되고 지원되지 않는 플랫폼은 개체(Android)의 View 문자열 표현으로 대체됩니다. 두 경우 모두 콘텐츠가 라디오 단추 원 옆에 가로로 맞춰 표시됩니다.
  • a가 ControlTemplate 적용 RadioButtonView 되면 모든 플랫폼의 속성에 a를 RadioButton.Content 할당할 수 있습니다. 자세한 내용은 RadioButton 모양 재정의를 참조 하세요.

문자열 기반 콘텐츠 표시

RadioButton 속성에 다음이 할당되면 텍스트 Contentstring표시됩니다.

<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에서는 속성에 RadioButton 다음이 할당되면 View임의의 콘텐츠를 Content 표시할 수 있습니다.

<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

참고 항목

a가 ControlTemplate 적용 RadioButtonView 되면 모든 플랫폼의 속성에 a를 RadioButton.Content 할당할 수 있습니다. 자세한 내용은 RadioButton 모양 재정의를 참조 하세요.

RadioButtons와 값 연결

RadioButton 개체에는 Value 라디오 단추와 연결할 선택적 고유 값을 정의하는 형식 object의 속성이 있습니다. 이렇게 하면 값이 RadioButton 콘텐츠와 다를 수 있으며 개체가 개체를 표시할 ViewRadioButton 특히 유용합니다.

다음 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>

이 예제에서는 각각 RadioButtonImage 문자열 기반 값을 정의하는 동시에 해당 콘텐츠로 포함됩니다. 이렇게 하면 검사 라디오 단추의 값을 쉽게 식별할 수 있습니다.

Group RadioButtons

라디오 단추는 그룹에서 작동하며 라디오 단추를 그룹화하기 위한 세 가지 방법이 있습니다.

  • 동일한 부모 컨테이너 내에 배치합니다. 이를 암시적 그룹화라고 합니다.
  • GroupName 그룹의 각 라디오 단추에 있는 속성을 동일한 값으로 설정합니다. 이를 명시적 그룹화라고 합니다.
  • 부모 컨테이너에 RadioButtonGroup.GroupName 연결된 속성을 설정하면 컨테이너에 있는 모든 RadioButton 개체의 속성이 설정 GroupName 됩니다. 이를 명시적 그룹화라고도 합니다.

Important

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 개체에 GroupNameLayout<View> 설정할 수 있는 형식string의 연결된 속성을 정의합니다. 이렇게 하면 모든 레이아웃을 라디오 단추 그룹으로 전환할 수 있습니다.

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

이 예제에서 StackLayoutRadioButton 속성은 해당 GroupName 속성으로 colors설정되며 상호 배타적입니다.

참고 항목

Layout<View> 연결된 속성을 설정하는 개체에 RadioButtonGroup.GroupName 해당 GroupName 속성을 설정하는 개체가 포함된 RadioButton 경우 속성 값이 RadioButton.GroupName 우선합니다.

RadioButton 상태 변경에 응답

라디오 단추의 상태는 선택되거나 선택되지 않은 두 가지 상태입니다. 라디오 단추가 검사 경우 해당 IsChecked 속성은 .입니다true. 라디오 단추가 해제되면 해당 속성false은 검사IsChecked. 같은 그룹의 다른 라디오 단추를 탭하여 라디오 단추를 지울 수 있지만 다시 탭하면 지울 수 없습니다. 그러나 해당 IsChecked 속성을 false로 설정하여 라디오 단추를 프로그래밍 방식으로 지울 수 있습니다.

이벤트 발생에 응답

IsChecked 사용자 또는 프로그래밍 방식 조작을 통해 속성이 CheckedChanged 변경되면 이벤트가 발생합니다. 이 이벤트에 대한 이벤트 처리기를 등록하여 변경에 응답할 수 있습니다.

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

코드 숨김에는 이벤트에 대한 처리기가 CheckedChanged 포함됩니다.

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

인수 senderRadioButton 이 이벤트를 담당합니다. 이를 사용하여 개체에 RadioButton 액세스하거나 동일한 CheckedChanged 이벤트 처리기를 공유하는 여러 RadioButton 개체를 구분할 수 있습니다.

속성 변경에 응답

클래스는 RadioButtonGroup 개체에 SelectedValueLayout<View> 설정할 수 있는 형식object의 연결된 속성을 정의합니다. 이 연결된 속성은 레이아웃에 정의된 그룹 내에서 검사 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 검사 속성으로 Value 업데이트됩니다RadioButton.

RadioButton 시각적 상태

RadioButton개체에는 CheckedUnchecked 검사 있거나 검사 않은 경우 RadioButton 시각적 변경을 시작하는 데 사용할 수 있는 시각적 상태가 있습니다.

다음 XAML 예제에서는 상태 및 Unchecked 상태에 대한 Checked 시각적 상태를 정의하는 방법을 보여줍니다.

<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>

이 예제에서 암시적 StyleRadioButton 개체를 대상으로 지정합니다. a CheckedVisualStateRadioButton 검사 때 해당 TextColor 속성이 값이 1인 Opacity 녹색으로 설정되도록 지정합니다. a UncheckedVisualState 가 un검사ed 상태이면 RadioButton 해당 TextColor 속성이 값이 0.5인 Opacity 빨간색으로 설정되도록 지정합니다. 따라서 전체적인 RadioButton 효과는 검사 않은 경우 빨간색과 부분적으로 투명하며 검사 때 투명도 없이 녹색이라는 것입니다.

Screenshot of RadioButton visual states

시각적 개체 상태에 대한 자세한 내용은 Xamarin.Forms 시각적 개체 상태 관리자를 참조하세요.

RadioButton 모양 재정의

기본적으로 개체는 RadioButton 플랫폼 렌더러를 사용하여 지원되는 플랫폼에서 네이티브 컨트롤을 활용합니다. 그러나 RadioButton 개체가 모든 플랫폼에서 동일한 모양을 갖도록 RadioButton 시각적 구조를 사용하여 ControlTemplate다시 정의할 수 있습니다. 클래스가 RadioButton 클래스에서 TemplatedView 상속되므로 가능합니다.

다음 XAML은 개체의 ControlTemplate 시각적 구조를 재정의 RadioButton 하는 데 사용할 수 있는 개체를 보여줍니다.

<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 , EllipseContentPresenter 개체의 Grid조합을 사용하여 개체의 RadioButton시각적 구조를 정의합니다. 이 예제에는 페이지에 있는 개체 RadioButton 의 속성에 ControlTemplate 할당 RadioButtonTemplate 하는 암시적 스타일도 포함되어 있습니다.

참고 항목

개체는 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을 사용하지 않도록 설정할 수 있습니다.