C# 如何检查是否已选择单选按钮,是否已为变量赋值

C# 如何检查是否已选择单选按钮,是否已为变量赋值,c#,wpf,C#,Wpf,我正在为一项作业编写一个距离计算器,其中一个要求是让用户选择他们想要的单位,以显示距离。我用哈弗森方程来计算距离。如果选择了按钮,我必须检查的代码是 private void单选按钮\u已选中(对象发送器,路由目标e) { if(MilesButton.Checked==true) { 半径=3956; } } 它给出了一个错误“事件只能出现在+=或-=的左侧”。 是否有更好的方法检查按钮是否已被选中?另外,如果我使用方法MilesButton.IsCheckedis,则会出现另一个错误“无法

我正在为一项作业编写一个距离计算器,其中一个要求是让用户选择他们想要的单位,以显示距离。我用哈弗森方程来计算距离。如果选择了按钮,我必须检查的代码是

private void单选按钮\u已选中(对象发送器,路由目标e)
{
if(MilesButton.Checked==true)
{
半径=3956;
}
}
它给出了一个错误“事件只能出现在+=或-=的左侧”。
是否有更好的方法检查按钮是否已被选中?另外,如果我使用方法
MilesButton.IsChecked
is,则会出现另一个错误“无法将类型'bool'隐式转换为'bool',存在显式转换(是否缺少强制转换?)

而不是
选中的
使用
IsChecked
属性:

private void单选按钮\u已选中(对象发送器,路由目标e)
{
if(MilesButton.IsChecked??false)
{
半径=3956;
}
}
您也可以使用如下方法:

if (MilesButton.IsChecked.GetValueOrDefault())

这个代码应该适合你

在XAML文件中:

    <Grid>
        <RadioButton x:Name="MilesButton" Content="MilesButton" HorizontalAlignment="Left" Margin="66,39,0,0" VerticalAlignment="Top" GroupName="distance" Checked="RadioButton_Checked"/>
        <RadioButton Content="KilometreButton" HorizontalAlignment="Left" Margin="66,59,0,0" VerticalAlignment="Top" GroupName="distance" Checked="RadioButton_Checked"/>
    </Grid>

我尝试使用IsChecked方法,但它也给了我一个错误。我编辑了该问题以显示它给出的错误。是否尝试了GetValuerDefault方法?
        private int radius = 0;
        public MainWindow()
        {
            InitializeComponent();
        }

        private void RadioButton_Checked(object sender, RoutedEventArgs e)
        {
            if (MilesButton.IsChecked == true)
            {
                radius = 3956;
            }
        }