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

gg0vcinb  于 2023-05-15  发布在  Mac
关注(0)|答案(1)|浏览(130)

我得到“对象引用未设置为对象的示例”错误,而试图打印我的Texfield的“StringValue”值以编程方式创建?

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中对象的示例。视图控制器。testt(系统。对象发送器,系统。EventArgs e)[0x00008] in/path to my folder/ViewController. cs:125在AppKit。NSTextField +_NSTextFieldDelegate。改变(基础)/Library/Frameworks/Xamarin中的NSNotification通知)[0x00011]。Mac. framework/Versions/6.10.0.17/src/Xamarin. Mac/NSTextField。g. cs:1093 at at(wrapper managed-to-native)AppKit。NS应用程序。AppKit中的NSApplicationMain(int,string [])。NS应用程序。主(系统。String [] args)[0x00040] in/Library/Frameworks/Xamarin. Mac. framework/Versions/6.10.0.17/src/Xamarin. Mac/AppKit/NSApplication。cs:100在myProject。MainClass。主(系统。String [] args)[0x00007] in/path to my folder/Main. cs:57

jm2pwxwz

jm2pwxwz1#

无法直接将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);
}

相关问题