09 WPF之RadioButton

WPF RadioButton 概述

RadioButton 是 WPF 中常用的单选控件,通常用于一组互斥的选项。其核心特性是同一组内的多个 RadioButton 只能有一个被选中。通过 GroupName 属性可以分组,未明确分组时,同一父容器内的 RadioButton 自动归为一组。

基本用法

XAML 中定义 RadioButton 的语法如下:

<RadioButton Content="选项1" IsChecked="True"/>
<RadioButton Content="选项2"/>
<RadioButton Content="选项3"/>

  • Content 属性设置显示文本或复杂内容。
  • IsChecked 属性控制选中状态(默认 false)。

分组控制

通过 GroupName 实现跨容器分组:

<StackPanel>
    <RadioButton Content="A组-选项1" GroupName="GroupA"/>
    <RadioButton Content="A组-选项2" GroupName="GroupA"/>
</StackPanel>
<StackPanel>
    <RadioButton Content="B组-选项1" GroupName="GroupB"/>
    <RadioButton Content="B组-选项2" GroupName="GroupB"/>
</StackPanel>

数据绑定

支持与 ViewModel 属性绑定:

<RadioButton Content="是" IsChecked="{Binding IsYes}"/>
<RadioButton Content="否" IsChecked="{Binding IsNo}"/>

ViewModel 需实现 INotifyPropertyChanged 接口通知状态变更。

自定义样式

通过修改 ControlTemplate 实现视觉定制:

<Style TargetType="RadioButton">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="RadioButton">
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center"/>
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

事件处理

常用 CheckedUnchecked 事件:

<RadioButton Content="选项" Checked="RadioButton_Checked"/>

C# 后台代码:

private void RadioButton_Checked(object sender, RoutedEventArgs e) {
    var radio = sender as RadioButton;
    MessageBox.Show(radio.Content.ToString());
}

与枚举绑定

结合 Enum 类型实现动态选项:

public enum Season { Spring, Summer, Autumn, Winter }

XAML 中使用 ObjectDataProvider

<Window.Resources>
    <ObjectDataProvider x:Key="SeasonData" MethodName="GetValues" 
                        ObjectType="{x:Type sys:Enum}">
        <ObjectDataProvider.MethodParameters>
            <x:Type TypeName="local:Season"/>
        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

<ItemsControl ItemsSource="{Binding Source={StaticResource SeasonData}}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <RadioButton Content="{Binding}" GroupName="Seasons"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

验证与错误提示

通过 ValidationRule 实现输入验证:

<RadioButton Content="同意条款">
    <RadioButton.IsChecked>
        <Binding Path="IsAgreed" UpdateSourceTrigger="PropertyChanged">
            <Binding.ValidationRules>
                <local:RequiredValidationRule/>
            </Binding.ValidationRules>
        </Binding>
    </RadioButton.IsChecked>
</RadioButton>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值