如何将数据从Main.cs传递到MainWindow.cs?

时间:2013-09-13 18:18:50

标签: mono gtk#

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

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以在构造函数中传递它(您不仅限于生成的构造函数,只需确保使用适当的参数调用base),或者您可以在MainWindow之前设置一些属性,然后再输入主循环。

以下是两种解决方案的示例。请注意,我总是从一个干净的Gtk#项目和MonoDevelop生成的Main.csMainWindows.cs开始,并使用不同的方法更改标签文本。请注意,如果需要,您可以直接更改标签标题,但这只是一个示例:同样可以应用于任何其他窗口小部件属性或窗口的一部分,需要更多逻辑而不仅仅是分配。

标签是使用stetic设计师创建的,名为label

方法1 - 更改MainWindow构造函数

让我们从MonoDevelop生成的代码开始,并将窗口标题作为参数传递给构造函数。这是MonoDevelop生成的代码:

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

这是我们修改构造函数的方法:

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;
    }
}

您还应更改Main,如下所示:

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();
}

方法2 - 使用属性

这很好,因为您可以在初始化后使用它来从应用程序的其他部分更改UI的某些部分。没有对构造函数进行任何更改,只需添加一个属性 - 或方法,以防需要传递多个参数。我将展示两者,从属性开始:

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

然后方法:

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

请注意,我明确指出了this,而MainWindowMain但是将其排除在外是安全的(并且很好)。

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(); } 的一个例子:

{{1}}