c# wpf中 一个RadioButton checked为true时 另一个RadioButton checked为false

在 WPF 中,RadioButton 控件默认具有互斥行为。当多个 RadioButton 共享同一个父容器或**相同的分组名称(GroupName)**时,选中其中一个会自动取消选中其他同组的 RadioButton。以下是实现互斥行为的两种常见方法:


方法 1:通过父容器自动分组

将多个 RadioButton 放在同一个父容器中(如 StackPanelGrid),无需额外代码即可实现互斥:

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

关键点总结

  1. 父容器分组:默认在同一容器内的 RadioButton 会自动互斥。
  2. GroupName 属性:跨容器时使用相同 GroupName 强制分组。
  3. 无需手动代码:WPF 内置逻辑会自动处理互斥,无需监听 Checked 事件。

通过以上方法,你可以轻松实现 RadioButton 的互斥行为。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值