UITextField null from another class

I have a class

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

Inside ViewController1.designer.cs I registered a UITextField

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

Here where I fight:

I have another class, ViewController2 , which inherits from ViewController1

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

Why, when inside ViewController2 my _textField always null when debugging?

+4
source share
2 answers

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

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

Btw: Your β€œfield” is a property. But the same is true for auto-properties.

You can 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 do not know hamarin. You need to call something like InitializeComponent(); inside the constructor? Does the ViewController1.designer.cs method have a method called so?

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

In WinForms, for example, a partial constructor class has a method that creates controls.

+6
source

Are you sure you created the binding for your Outlet field, as described in this lesson?

http://developer.xamarin.com/guides/ios/user_interface/controls/part_1_-_creating_user_interface_objects/

Click a user interface object; then Control Drag to .h file. To control the drag and drop, hold down the control key, then click and hold the user interface object that you create to exit (or action). Continue to hold down the Control key while dragging and dropping into the header file. Complete the drag and drop below the @interface definition. A blue line should appear with the words Insert Outlet or Outlet Collection, as shown in the screenshot below.

When you release the click, you will be asked to specify a name for the Outlet, which will be used to create a C # property that can be referenced in the code:

Also, you should not register anything with Designer.cs, it should be generated automatically, if you did not follow the drag and drop steps and tried to add code to the constructor manually, it will not bind correctly.

iOS doesn't follow C # principles; iOS only binds the board objects defined in the .h file included in the application. Although you do not add the .h file, but Xamarin creates it automatically and places it in the application.

+2
source

All Articles