如何获取在 Xamarin MacOS 中以编程方式创建的 NSTextField 的值?

How to get value of a NSTextField which is created programmatically in Xamarin MacOS?

我在尝试打印以编程方式创建的 Texfield 的 "StringValue" 值时出现 "Object reference not set to an instance of an object" 错误?

NSTextField[] t = new NSTextField[1];

public override void ViewDidLoad()
{
 base.ViewDidLoad();

 t[0] = new NSTextField();
 t[0].Frame = new CoreGraphics.CGRect(20, 1, 200, 20);
 t[0].Tag = 0;
 t[0].Identifier = "0";
 t[0].StringValue = "yahoo";
 t[0].Bordered = true;
 t[0].Changed += new EventHandler(testt);
 this.myNSBox.AddSubview(t[0]);
}

public void testt(Object sender, EventArgs e) 
{
 NSTextField check = sender as NSTextField;
 //var check = sender as NSTextField; this is also not working
 Console.WriteLine(check.StringValue);
}

System.NullReferenceException: 对象引用未设置为对象的实例 在 myProject.ViewController.testt(System.Object 发件人,System.EventArgs e)[0x00008] 中 /我文件夹的路径 /ViewController.cs:125 在 AppKit.NSTextField+_NSTextFieldDelegate.Changed(Foundation.NSNotification 通知)[0x00011] 在 /Library/Frameworks/Xamarin.Mac.framework/Versions/6.10.0.17/src/Xamarin.Mac/NSTextField.g.cs:1093 at at (wrapper managed-to-native) AppKit.NSApplication.NSApplicationMain(int,string[]) 在 AppKit.NSApplication.Main (System.String[] args) [0x00040] 在 /Library/Frameworks/Xamarin.Mac.framework/Versions/6.10.0.17/src/Xamarin.Mac/AppKit/NSApplication.cs:100 在 myProject.MainClass.Main (System.String[] args) [0x00007] 中 /我文件夹的路径 /Main.cs:57

您无法将 sender 直接转换为 NSTextField

尝试改变

public void testt(Object sender, EventArgs e) 
{
   NSTextField check = sender as NSTextField;
   //var check = sender as NSTextField; this is also not working
   Console.WriteLine(check.StringValue);
}

public void testt(Object sender, EventArgs e) 
{
   NSNotification notification =  sender as NSNotification;
   NSTextField check = notification.Object as NSTextField;
   Console.WriteLine(check.StringValue);
}