Freitag, 19. April 2013

Binding a ViewModel to a simple UITableView using MvvmCross


In this blog entry I will describe how to show a simply UITableView which is bound to a list of custom objects.

I've started a while ago writing my first TableView. I used the CustomerManagement-Sample as kind of a template. This can be found here:

As I had not that much of an idea how it really works, I just implemented the same classes as which they are available in the sample:
  • A custom TableSource-class
  • A custom Cell-class
This actually did not really work, I've ended up writing a question on Stackoverflow:

With the answer from Stuart and some additional hints he gave me in the chat I knew, that I may have to read  and watch some additional stuff. 
So for everyone starting with cells in MvvmCross, take an hour and watch the following video:

This should give you a greate overview on how to create/bind and use custom cells.

But what is the easy way to go?
As I just want to bind a single text to the list there must be a simpler solution for this.Stuart already mentioned this solution in his stackoverflow post. It is implemented in the following sample:

It is really easy:
Here the implementation of my controller which is all I had to do: (no custom TableSource/cell/xibs.. whatever :-))
[MvxViewFor(typeof(MainViewModel))]
  public partial class TestViewController : MvxViewController
 {
  public TestViewController () : base ("TestViewController", null)
  {
  }
  
  public override void ViewDidLoad ()
  {
   base.ViewDidLoad ();
 
         var source = new MvxStandardTableViewSource(UiTableViewOutlet, "TitleText Name;");
 
   this.AddBindings(new Dictionary()
                    {
    {source, "ItemsSource MyList;"}
   });
   
   UiTableViewOutlet.Source = source;
   UiTableViewOutlet.ReloadData();
  }
 }

As you can see, you can use the MvxStandardTableViewSource. This class we have to support with a reference to our UITableView-Outlet and the binding-description. This binding-description is executed on every item in the list we bound to ItemSource in the lines 14 to 16.

Make sure you set the source to the UiTableView and call ReloadData. And that's it!
Thanks to Stuart for the help and write a comment should you have any additional problems with UiTableViews :-)

1 Kommentar:

  1. If your view is just one big table, then you might also consider inheriting from mvxtableviewcontroller instead of using mvxviewcontroller with a XIB

    AntwortenLöschen