在 WPF 中,RadioButton
控件默认具有互斥行为。当多个 RadioButton
共享同一个父容器或**相同的分组名称(GroupName)**时,选中其中一个会自动取消选中其他同组的 RadioButton
。以下是实现互斥行为的两种常见方法:
方法 1:通过父容器自动分组
将多个 RadioButton
放在同一个父容器中(如 StackPanel
、Grid
),无需额外代码即可实现互斥:
<StackPanel>
<RadioButton Content="选项1" IsChecked="True"/>
<RadioButton Content="选项2"/>
<RadioButton Content="选项3"/>
</StackPanel>
方法 2:通过 GroupName 手动分组
如果 RadioButton
不在同一个父容器中,可以通过设置相同的 GroupName
强制分组:
<RadioButton GroupName="MyGroup" Content="选项1" IsChecked="True"/>
<RadioButton GroupName="MyGroup" Content="选项2"/>
<RadioButton GroupName="MyGroup" Content="选项3"/>
验证绑定(可选)
如果使用 MVVM 模式,可以通过数据绑定实现更复杂的逻辑。例如:
// ViewModel
public class MyViewModel : INotifyPropertyChanged
{
private string _selectedOption;
public string SelectedOption
{
get => _selectedOption;
set
{
_selectedOption = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string name = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
<!-- XAML -->
<StackPanel DataContext="{StaticResource MyViewModel}">
<RadioButton GroupName="MyGroup" Content="选项1"
IsChecked="{Binding SelectedOption, Converter={StaticResource StringToBoolConverter}, ConverterParameter=Option1}"/>
<RadioButton GroupName="MyGroup" Content="选项2"
IsChecked="{Binding SelectedOption, Converter={StaticResource StringToBoolConverter}, ConverterParameter=Option2}"/>
</StackPanel>
关键点总结
- 父容器分组:默认在同一容器内的
RadioButton
会自动互斥。 - GroupName 属性:跨容器时使用相同
GroupName
强制分组。 - 无需手动代码:WPF 内置逻辑会自动处理互斥,无需监听
Checked
事件。
通过以上方法,你可以轻松实现 RadioButton
的互斥行为。