WPF桌面端开发1-常用组件RadioButton

设置分组

在 WPF 中,要将多个 RadioButton 设定为一组(即互斥选择,只能选中其中一个),主要有以下两种方法:

通过容器自动分组

RadioButton 位于同一个容器(如 StackPanelGridPanel 等)中,且未指定 GroupName 时,WPF 会自动将它们视为一组。

1
2
3
4
5
6
7
8
9
10
11
12
<!-- StackPanel 内的 RadioButton 自动形成一组 -->
<StackPanel>
<RadioButton Content="选项A" />
<RadioButton Content="选项B" />
<RadioButton Content="选项C" />
</StackPanel>

<!-- 另一个容器内的 RadioButton 形成另一组 -->
<Grid>
<RadioButton Content="选项X" />
<RadioButton Content="选项Y" />
</Grid>

使用相同的 GroupName 属性

最简单的方式是给同一组的 RadioButton 设置相同的 GroupName 属性值。

1
2
3
4
5
6
7
8
9
<StackPanel>
<!-- 这三个 RadioButton 属于同一组 -->
<RadioButton Content="选项1" GroupName="MyGroup" />
<RadioButton Content="选项2" GroupName="MyGroup" />
<RadioButton Content="选项3" GroupName="MyGroup" />

<!-- 这个 RadioButton 属于另一组 -->
<RadioButton Content="其他选项" GroupName="AnotherGroup" />
</StackPanel>
  • 同一 GroupNameRadioButton 会自动形成互斥关系
  • 不同 GroupNameRadioButton 互不影响

注意事项

  • GroupName 的优先级高于容器分组:如果同一容器内的 RadioButton 设置了不同的 GroupName,会按照 GroupName 进行分组
  • 可以通过 IsChecked 属性设置默认选中项:

    1
    <RadioButton Content="默认选中" GroupName="MyGroup" IsChecked="True" />
  • 分组仅影响选择行为,不影响布局,可根据需要自由安排布局结构

根据实际需求选择合适的分组方式即可,通常简单场景下使用容器自动分组更便捷,复杂场景(如跨容器分组)则需要显式指定 GroupName