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>
事件处理
常用 Checked 和 Unchecked 事件:
<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>
5万+

被折叠的 条评论
为什么被折叠?



