C# - 当前上下文中不存在变量引用

时间:2016-05-31 10:55:25

标签: c# list combobox

我在主窗口类中有这个代码,我在其中声明了一些值以放入ListForTesting列表并使测试显示在组合框中。后来还有另一个组合框依赖于第一个组合框,我向你展示下面的代码:

值得一提的是,我对C#完全陌生。仅以VBA编码。我是机械工程师,不是软件:)。

主窗口代码

public MainWindow()
{
    InitializeComponent();
    grid_projectConfig.Visibility = Visibility.Collapsed;
    grid_projectOverview.Visibility = Visibility.Collapsed;
    grid_test.Visibility = Visibility.Collapsed;
    grid_reports.Visibility = Visibility.Collapsed;

    //ListForTesting holds the hardcoded set of tests and manoeuvres
    List<HelpClass.TestID> ListForTesting = new List<HelpClass.TestID>();

    //TestObject holds the test name, ID and all the manoeuvres related to it
    HelpClass.TestID TestObject = new HelpClass.TestID();
    TestObject.testName = "Steady State";
    TestObject.ID = 0;
    //Manoeuvre holds the manoeuvre name and its ID
    TestObject.Manoeuvres = new List<HelpClass.ManoeuvresID>();
    HelpClass.ManoeuvresID Manoeuvre = new HelpClass.ManoeuvresID();
    Manoeuvre.manName = "30 kph";
    Manoeuvre.manID = 0;
    //add the Manoeuvre to the TestObject
    TestObject.Manoeuvres.Add(Manoeuvre);
    //create new Manoeuvre
    Manoeuvre = new HelpClass.ManoeuvresID();
    Manoeuvre.manName = "50 kph";
    Manoeuvre.manID = 1;
    TestObject.Manoeuvres.Add(Manoeuvre);
    //add the TestObject to the ListForTesting
    ListForTesting.Add(TestObject);


    //display the tests in a combobox
    combobox_testType.ItemsSource = ListForTesting.Select(t => t.testName);
}

第二个组合框代码

public void combobox_testType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    combobox_testType.ItemsSource = ListForTesting[1].Manoeuvres.Select(t => t.manName);
}

这最后一行代码不起作用,因为它告诉我它在当前上下文中不存在。

2 个答案:

答案 0 :(得分:3)

问题是变量ListForTesting scope :通过在MainWindow构造函数中声明它,您可以限制其对该方法的可见性。

要允许从您班级中的其他方法访问ListForTesting(即:combobox_testType_SelectionChanged),您必须将其声明为类级变量,如下所示:

public class MainWindow : Window
{
    private List<HelpClass.TestID> ListForTesting; // Variable declaration

    public MainWindow()
    {
        // code

        ListForTesting = new List<HelpClass.TestID>(); // Initialization

        // code
    }
}

答案 1 :(得分:1)

变量ListForTesting在构造函数的范围内。你需要将变量移出那里,以便可以在课堂的其他地方访问它。

List<HelpClass.TestID> ListForTesting;

public MainWindow()
{
...
   ListForTesting = new List<HelpClass.TestID>();
...
}