Как получить значение NSTextField, который создается программно в Xamarin MacOS? - PullRequest
0 голосов
/ 01 апреля 2020

Я получаю сообщение об ошибке «Ссылка на объект не установлена ​​на экземпляр объекта» при попытке напечатать значение «StringValue» моего Texfield, созданного программным способом?

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] в / path к моей папке /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 (обертка управляемая родному) 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 at myProject.MainClass.Main (System.String [] args) [0x00007] в / path к моей папке /Main.cs:57

1 Ответ

0 голосов
/ 02 апреля 2020

Невозможно преобразовать 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);
}
...