你错过了使用指令或程序集引用吗? C#出错

时间:2014-06-12 13:30:24

标签: c# wpf

我正在尝试创建一个非常简单的C#程序。

这是xaml文件:

<Window x:Class="HelloWPFApp.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBlock HorizontalAlignment="Left" Margin="104,72,0,0" TextWrapping="Wrap" Text="Select a message option and then choose the Display button" VerticalAlignment="Top"/>
        <RadioButton x:Name="RadioButton1" Content="Hello;" HorizontalAlignment="Left" Margin="104,138,0,0" VerticalAlignment="Top" Checked="RadioButton1_Checked"/>
        <RadioButton x:Name="RadioButton2" Content="Goodbye;" HorizontalAlignment="Left" Margin="342,138,0,0" VerticalAlignment="Top"/>
        <Button Content="Display" HorizontalAlignment="Left" Margin="211,208,0,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>

    </Grid>
</Window>

这是.cs文件:

using....
namespace HelloWPFApp
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (RadioButton1.IsChecked == true)
                MessageBox.Show("Hello");
            else
                MessageBox.Show("Goodbye");

        }
    }
}

这是我得到的错误:

  

&#39; HelloWPFApp.MainWindow&#39;不包含的定义   &#39; RadioButton1_Checked&#39;没有扩展方法&#39; RadioButton1_Checked&#39;   接受第一个类型&#39; HelloWPFApp.MainWindow&#39;可能   发现(您是否缺少using指令或程序集引用?)

你能告诉我这是什么问题吗?

2 个答案:

答案 0 :(得分:7)

您已在xaml代码中定义了一个事件处理程序

 <RadioButton x:Name="RadioButton1" Content="Hello;" HorizontalAlignment="Left" Margin="104,138,0,0" VerticalAlignment="Top" Checked="RadioButton1_Checked"/>

但是你没有在代码隐藏中定义相同的内容。这就是导致问题的原因。从上面的单选按钮中删除Checked Event,或在后面的代码中定义一个事件处理程序。

答案 1 :(得分:2)

定义检查事件单选按钮的方法, 将其添加到MainWindow.xaml.cs

void RadioButton1_Checked(object sender, RoutedEventArgs e)
{
    //add your job here
}

或替换此行

<RadioButton x:Name="RadioButton1" Content="Hello;" HorizontalAlignment="Left" Margin="104,138,0,0" VerticalAlignment="Top" Checked="RadioButton1_Checked"/>

这一个

<RadioButton x:Name="RadioButton1" Content="Hello;" HorizontalAlignment="Left" Margin="104,138,0,0" VerticalAlignment="Top"/>