Question

I want to add a drawing to the main window.
But when I'm trying to access the window widget it says:

error CS0120: An object reference is required to access non-static member 'MainWindow.win'

Could anyone explain what this means and how to fix this?

This is the code :

using Gtk;
using System;
using Cairo;

public class MainWindow {   

    public Window win = new Window("Traffic Light Simulator 0.1");
    Fixed winFix = new Fixed();
    DrawingArea rightSeparator = new DrawingArea();


    MainWindow() {
        win.SetSizeRequest(800, 600);
        win.Resizable = false;
        win.DeleteEvent += delegate { Application.Quit(); };
        win.SetPosition(WindowPosition.Center);
        win.ModifyBg(StateType.Normal, new Gdk.Color(255, 255, 255));

        rightSeparator.SetSizeRequest(10, 600);
        rightSeparator.ModifyBg(StateType.Normal, new Gdk.Color(200, 200, 200));

        winFix.Put(rightSeparator, 580, 0);


        win.Add(winFix);
        win.ShowAll();
    }


    public static void Main() {
        Application.Init();
        new MainWindow();
        Application.Run();
    }

}

public class Light {
    DrawingArea darea = new DrawingArea();

    Light(int x, int y, int size) {

        MainWindow.win.Add(darea);

    }
}
Was it helpful?

Solution

There seems to be a misconception about what you want to do:

  • You seem to want to call Add() on the MainWindow instance of your application
  • Your code tries to access the MainWindow class

To fix this, you need to hold a reference to your main window:

  • new MainWindow(); should be MainWindow myMainWindow=new MainWindow();
  • Light(int x, int y, int size) { MainWindow.win.Add(darea); } should be Light(MainWindow theMainWindow, int x, int y, int size) { theMainWindow.win.Add(darea); }
  • finally you need to glue the pieces together, so that the variable, that holds the reference, is passed into Light()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top