如何找出选择的按钮?

sof*_*fun 4 c# wpf xaml

<GroupBox x:Name="groupBox" Header="Operating System" HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Height="74" Width="280">
        <StackPanel>
            <RadioButton GroupName="Os" Content="Windows 7 (64-bit)" IsChecked="True"/>
            <RadioButton GroupName="Os" Content="Windows 7 (32-bit)" />
        </StackPanel>
    </GroupBox>
Run Code Online (Sandbox Code Playgroud)

我的应用程序中有几个单选按钮组

如何使用C#访问Code-Behind中已检查的哪一个?

是否绝对有必要在每个RadioButton上使用x:Name =还是有更好的方法吗?

代码示例总是受到赞赏

Bra*_*NET 5

是! 有一种更好的方法,称为绑定.在绑定之外,你几乎陷入困境(我可以想象分别处理所有已检查的事件,并分配给枚举,但这真的更好吗?)

对于单选按钮,通常使用a enum来表示所有可能的值:

public enum OsTypes
{
    Windows7_32,
    Windows7_64
}
Run Code Online (Sandbox Code Playgroud)

然后将每个单选按钮绑定到VM上的全局"选定"属性.你需要ValueEqualsConverter这个:

    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.Equals(parameter);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return ((bool)value) ? parameter : Binding.DoNothing;
    }
Run Code Online (Sandbox Code Playgroud)

然后你的单选按钮看起来像:

<RadioButton Content="Windows 7 32-bit"
             IsChecked= "{Binding CurrentOs, 
                         Converter={StaticResource ValueEqualsConverter},
                         ConverterParameter={x:Static local:OsTypes.Windows7_32}}"
Run Code Online (Sandbox Code Playgroud)

当然,您的VM中有一个属性:

public OsTypes CurrentOs {get; set;}
Run Code Online (Sandbox Code Playgroud)

否x:名称,复杂的switch语句或其他任何内容.漂亮,干净,设计精良.MVVM 工作与WPF,用它!