C# 如何将参数传递给Gtk中按钮触发的函数?
我试图在Gtk中的FileChooser中传递文件,并使用从该文件读取的第二个按钮来传递它们。我无法将FileChooser传递给函数,当单击第二个按钮时会触发该函数C# 如何将参数传递给Gtk中按钮触发的函数?,c#,mono,gtk#,C#,Mono,Gtk#,我试图在Gtk中的FileChooser中传递文件,并使用从该文件读取的第二个按钮来传递它们。我无法将FileChooser传递给函数,当单击第二个按钮时会触发该函数 namespace SharpTest{ internal static class SharpTest{ public static void Main(string[] args){ Application.Init(); var window = ne
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
}
}
}
FileChooserButtonscanButton中的FileName属性保存所选文件的名称。您面临的问题是无法从ScanFile()访问按钮,因为它位于Main()之外,而scanButton是其中的本地引用
此外,您正在使用一种老式的方式创建事件处理程序。实际上,您可以为此目的使用lambdas(最简单的选项),并以您喜欢的方式修改ScanFile()调用中的参数
因此,不是:
scanButton.Clicked += ScanFile;
您可以将其更改为:
scanButton.Clicked += (obj, evt) => ScanFile( fileButton.Filename );
如果将ScanFile()更改为:
使用该lambda,您将创建一个匿名函数,该函数接受对象obj(事件的发送者)和EventArgsargs对象(事件的参数)。您对该信息不做任何处理,因此您会忽略它,因为您只对scanButton中的FileName属性的值感兴趣
希望这有帮助。非常感谢。另外,如果你有一些网站或文章推荐给我,我将不胜感激。你可以在这里了解Gtk。另外,我在这里有一个带有一些演示的存储库:再次感谢,你保存了我的项目。好的,如果我想更改整个窗口怎么办。例如,当我单击按钮时,我想从窗口中删除所有内容,并用一些文本显示标签。您可以有一个隐藏面板,当事件到达时,隐藏当前面板并显示隐藏面板。如果你仍然需要帮助,你必须提出一个不同的问题。
private static void ScanFile(string fn)
{
// ... do something with the file name in fn...
}