0

如何将数据从 Main.cs 传递到 MainWindow.cs?说要填充使用 Setic 设计器创建的标签?

提前致谢!

4

1 回答 1

0

You can pass it in the constructor (you're not limited to the generated constructor, just make sure to call base with appropriate arguments) or you can set some properties on MainWindow before entering the main loop.

Here are examples for both solutions. Note that I always start with a clean Gtk# project and MonoDevelop-generated Main.cs and MainWindows.cs and change the label text using different methods. Note that you can probably change the label title directly if you want, but this is just an example: the same can be applied to any other widget property or part of the window that require more logic than just an assignment.

The label was created using the stetic designer and named just label.

Method 1 - Changing the MainWindow constructor

Let's start from the code generated by MonoDevelop and pass the window title as an argument to the constructor. This is the code generated by MonoDevelop:

public partial class MainWindow : Gtk.Window
{
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        this.Build();
    }
}

And this how we modify the constructor:

public partial class MainWindow : Gtk.Window
{
    public MainWindow(string labelText) : base(Gtk.WindowType.Toplevel)
    {   // Note param here   ^^^^^^^^^            
        this.Build();
        // And how we use it on the following line
        this.label.text = labelText;
    }
}

You should also change Main as follows:

public static void Main (string[] args)
{
    Application.Init();
    // Note the extra parameter on next line.
    var win = new MainWindow("Your label text here");
    win.ShowAll();
    Application.Run();
}

Method 2 - Using a property

This is nice because you can use it after initialization to change some parts of the UI from other parts of your application. No changes to the constructor, you just add a property - or method in case you need to pass several parameters. I'll show both, starting with property:

public string LabelText {
    get { return label.Text;  }
    set { this.label.Text = value; }
}

Then method:

public void SetLabelText(string text)
{
    this.label.Text = text;
}

Note that I made this explicit and it is the MainWindow but it is safe (and good) to leave it out.

An example of Main:

public static void Main (string[] args)
{
    Application.Init();
    var win = new MainWindow();
    win.ShowAll();
    // Using the property
    win.LabelText = "Your label text here";
    // Or the method
    win.SetLabelText("Another label text");
    Application.Run();
}
于 2013-09-13T18:23:53.023 回答