我如何绑定是否选择某个组的任何/无“RadioButton”

本文关键字:任何 RadioButton 何绑定 绑定 选择 是否 | 更新日期: 2023-09-27 18:01:34

如何绑定是否检查某组的RadioButton ?

假设有4个RadioButton s。最初没有选中它们,因此"next"按钮被禁用。用户必须做出选择,才能启用"下一步"按钮,并能够继续。

我如何绑定是否选择某个组的任何/无“RadioButton”

第一个解决方案效率不高,因为每个新的RadioButton都需要添加额外的DataTrigger:

  <StackPanel>
    <RadioButton Name="x1"/>
    <RadioButton Name="x2"/>
    <RadioButton Name="x3"/>
    <RadioButton Name="x4"/>
    <Button Content="Click">
        <Button.Style>
            <Style TargetType="Button">
                <Setter Property="IsEnabled" Value="False"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding ElementName=x1, Path=IsChecked}" Value="True">
                        <Setter Property="IsEnabled" Value="True"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=x2, Path=IsChecked}" Value="True">
                        <Setter Property="IsEnabled" Value="True"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=x3, Path=IsChecked}" Value="True">
                        <Setter Property="IsEnabled" Value="True"/>
                    </DataTrigger>
                    <DataTrigger Binding="{Binding ElementName=x4, Path=IsChecked}" Value="True">
                        <Setter Property="IsEnabled" Value="True"/>
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>
</StackPanel>

后者又基于MVVM。你在ViewModel中创建属性IsChecked,当任何RadioButton被选中时,它将IsChecked值设置为True,你的按钮基于这个值设置它的IsEnabled属性。

XAML :

<StackPanel>
    <StackPanel.Resources>
        <Style TargetType="RadioButton">
            <Setter Property="Command" Value="{Binding RadioButtonCheckedCommand}"/>
        </Style>
    </StackPanel.Resources>
    <RadioButton Name="x1"/>
    <RadioButton Name="x2"/>
    <RadioButton Name="x3"/>
    <RadioButton Name="x4"/>
    <Button Content="Click" IsEnabled="{Binding IsChecked}"/>
</StackPanel>

ViewModel :

    class MainViewModel : INotifyPropertyChanged
{
    private bool _isChecked;
    public bool IsChecked
    {
        get { return _isChecked; }
        set
        {
            _isChecked = value;
            OnPropertyChanged();
        }
    }
    private RelayCommand _radioButtonCheckedCommand;
    public RelayCommand RadioButtonCheckedCommand
    {
        get
        {
            return _radioButtonCheckedCommand ??
                   (_radioButtonCheckedCommand = new RelayCommand(() => IsChecked = true));
        }
    }
    public void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        if (PropertyChanged != null)
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
    public event PropertyChangedEventHandler PropertyChanged;
}