如何将参数传递给 Gtk# 中由 Button 触发的函数?
How to pass argument to function triggered by Button in 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
}
}
}
FileName 属性 in FileChooserButton scanButton 保存的名称选择的文件。您面临的问题是您无法从 ScanFile() 访问按钮,因为它在 Main() 和 之外scanButton 是里面的局部引用。
此外,您使用的是创建事件处理程序的老式方式。您实际上可以为此目的使用 lambda(最简单的选项),并按照您喜欢的方式修改对 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 对象(事件的参数)。您没有对该信息做任何事情,所以您忽略了它,因为您只对 FileName 属性 in scanButton[=40] 的值感兴趣=].
希望对您有所帮助。
我正在尝试在 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
}
}
}
FileName 属性 in FileChooserButton scanButton 保存的名称选择的文件。您面临的问题是您无法从 ScanFile() 访问按钮,因为它在 Main() 和 之外scanButton 是里面的局部引用。
此外,您使用的是创建事件处理程序的老式方式。您实际上可以为此目的使用 lambda(最简单的选项),并按照您喜欢的方式修改对 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 对象(事件的参数)。您没有对该信息做任何事情,所以您忽略了它,因为您只对 FileName 属性 in scanButton[=40] 的值感兴趣=].
希望对您有所帮助。