Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UITextField null from different class

I have the class

public ViewController1 (IntPtr handle) : base (handle){}

Inside the ViewController1.designer.cs I have registered a UITextField

[Outlet]
UIKit.UITextField _textField { get; set; }

Here's where I am struggling:

I have another class, ViewController2 that inherits from ViewController1

public class ViewController2 : ViewController1
{
    public ViewController2 (IntPtr handle) : base (handle){}
}

Why is it that when inside ViewController2 that my _textField is always null when debugging?

like image 659
jipot Avatar asked Feb 09 '23 10:02

jipot


1 Answers

Have you initialized _textField? Like _textField = new UIKit.UITextField();. Because all the fields are nulled when a class is created. After creating ViewController1 or ViewController2, _textField is null, unless you assigned it something in the constructor.

More precisely, every field T field is intialized to default(T), which, for reference types, is null.

Btw.: Your "field" is a property. But the same is true for auto-properties.

You could initialize _textField like this in the constructor:

public partial class ViewController1
{
    public ViewController1 (IntPtr handle)
        : base(handle)
    {
        _textField = new UIKit.UITextField();
    }
}

I must admit that I don't know xamarin. Do you have to call something like InitializeComponent(); inside the constructor? Does ViewController1.designer.cs have a method called like this?

    public ViewController1 (IntPtr handle)
        : base(handle)
    {
        InitializeComponent();
    }

In WinForms, for instance, the designer partial class has such a method, which creates the controls.

like image 188
Olivier Jacot-Descombes Avatar answered Feb 12 '23 00:02

Olivier Jacot-Descombes