Wallace Banter
Wallace Banter

Reputation: 165

How to populate a table from a controller in Xamarin?

I'm currently populating a tableview like this:

public class DataViewController : UIViewController
{
    public override void ViewDidLoad ()
{
     base.ViewDidLoad ();
         //...
         this.DataTableView.Delegate = new DataTableViewSource();
    }

    public class DataTableViewSource : UITableViewSource
    {
         //UITableSource methods
    }
}

Because of this I have to pass my data to the DataViewTableSource somehow. This works, but I prefer managing my table data in the UIViewController itself (including the cells etc.). Kind of like how Objective-C works with the UITableViewDataSource protocol (interface) implementation.

Is this possible in Xamarin?

Upvotes: 3

Views: 1672

Answers (1)

Leon Lucardie
Leon Lucardie

Reputation: 9730

This is possible if you use Xamarin.iOS 7.0 or up and make your viewcontroller implement IUITableViewDataSource or IUITableViewDelegate.

Example:

public class DataViewController : UIViewController, IUITableViewDataSource, IUITableViewDelegate
{
    public override void ViewDidLoad ()
    {
         base.ViewDidLoad ();
         //...
         this.DataTableView.WeakDataSource = this; //Make sure to use WeakDataSource instead of DataSource
    }

    public override int RowsInSection (UITableView tableview, int section){

    }

    public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
    {

    }
}

If you want to implement any methods that are marked as Optional in Objective-C you should implement them without the override keyword and add an export attribute with their Objective-C equivalent to them.

Like this:

[Export ("tableView:accessoryButtonTappedForRowWithIndexPath:")]
public void AccessoryButtonTapped (UITableView tableView, NSIndexPath indexPath)
{
}

If you have a more recent version of Xamarin Studio/Xamarin.iOS for Visual Studio, intellisense should automatically add this export attribute and remove the override keyword when adding methods like these.

Upvotes: 1

Related Questions