如何将参数传递给Gtk#中的Button触发的函数?

时间:2018-01-15 15:15:50

标签: c# mono gtk#

我试图在Gtk#中的FileChooser中传递文件,并使用此文件中的第二个按钮读取它们。我无法将FileChooser传递给函数,该函数在单击第二个按钮时触发。

namespace SharpTest{
    internal static class SharpTest{
        public static void Main(string[] args){
            Application.Init();

            var window = new Window("Sharp Test");
            window.Resize(600, 400);
            window.DeleteEvent += Window_Delete;

            var fileButton = new FileChooserButton("Choose file", FileChooserAction.Open);

            var scanButton = new Button("Scan file");
            scanButton.SetSizeRequest(100, 50);
            scanButton.Clicked += ScanFile;

            var boxMain = new VBox();
            boxMain.PackStart(fileButton, false, false, 5);
            boxMain.PackStart(scanButton, false, false, 100);
            window.Add(boxMain);

            window.ShowAll();
            Application.Run();
        }

        private static void Window_Delete(object o, DeleteEventArgs args){
            Application.Quit ();
            args.RetVal = true;
        }

        private static void ScanFile(object sender, EventArgs eventArgs){
            //Read from file
        }
    }
}

1 个答案:

答案 0 :(得分:1)

FileChooserButton scanButton 中的 FileName 属性包含所选文件的名称。您遇到的问题是您无法从 ScanFile()访问该按钮,因为它位于 Main()之外,而 scanButton 是本地的在里面引用。

此外,您正在使用创建事件处理程序的旧式方式。实际上,您可以将lambdas用于此目的(最简单的选项),并按照您喜欢的方式修改对 ScanFile()的调用中的参数。

所以,而不是:

scanButton.Clicked += ScanFile;

您可以将其更改为:

scanButton.Clicked += (obj, evt) => ScanFile( fileButton.Filename );
只要您将 ScanFile()更改为:

就可以解决问题

private static void ScanFile(string fn)
{
   // ... do something with the file name in fn...
}

使用该lambda,您将创建一个匿名函数,该函数接受对象 obj (事件的发送者)和 EventArgs args object(事件的参数)。你对这些信息一无所知,所以你放弃它,因为你只对 scanButton FileName 属性的值感兴趣。

希望这有帮助。