Databinding a ListView – Part 2 – Writing a Xamarin.Forms App

Start here: Part 1 – Sara can has MVVM for what I’m building in this series.

Note: Matt Soucoup has been awesome helping me break my mental barrier to using services in a MVVM design pattern. Go check out his Xamarin blog. Consider my blog posts my homework assignments. The only way I truly grok a concept is when I can explain it to someone else.

To follow along, go to my ListViewInTabbedControl and  `git checkout tags/listview-created` or view the diff here.

What I learned

  • Do *NOT* use the ListView’s ObservableCollection as the “source of truth” for a list of fabrics. Forget about the ObservableCollection. It is only for the PageOneViewModel – this is the heart of the issue I have in my head. The source of truth for “What is my official list of Fabrics to iterate through on the other Tabbed page?” comes from a FabricDataService, which I’ll discuss later in this series.
  • Alt+Enter is the Ctrl+. for VS on Mac

1) Add a Fabric Model that derives from ObservableObject

ObservableObject is needed so that when the user edits items, the ListView will get those updates. For example,

    public class Fabric : ObservableObject
    {
        private string name;
        private int seconds;

        public Fabric(string Name, int Seconds)
        {
            this.Name = Name;
            this.Seconds = Seconds;
        }

        public string Name { get => name; set => SetProperty(ref name, value); }

        public int Seconds { get => seconds; set => SetProperty(ref seconds, value); }

        public override string ToString()
        {
            return this.Name + " " + this.Seconds;
        }
    }

2) In PageOneViewModel create an observable collection

For example,

public ObservableCollection OCFabrics { get; set; }

 Note to self: This ObservableCollection is *only* for the View to display items in the ListView. It’s “transient” to the ListView. Do *NOT* use this as the “source of truth” for fabrics, i.e. do not use as the official list of fabrics the rest of the app should use, e.g. which fabric are we on? what’s the seconds remaining for the current fabrics? This has been my biggest mental hurdle in MVVM.

If this isn’t the source of truth, what is? Enter a FabricDataService! More on this in my upcoming blog posts.

Let’s initialize this ObservableCollection with some data. we’ll change where this data comes from in a couple of blog posts using a FabricDataService. We just want a working list view for now.

public PageOneViewModel(INavigation Navigation) {

   OCFabrics = new ObservableCollection<Fabric>();

   OCFabrics.Add(new Fabric("fabric1", 5));
   OCFabrics.Add(new Fabric("fabric2", 5));
   OCFabrics.Add(new Fabric("fabric3", 5));

   Title = "Page One from VM";
   this.Navigation = Navigation;
}

3) In PageOneViewModel create a ListView.

Note the ItemsSource, SelectedItem, Binding Name, and Binding Seconds.

<ListView ItemsSource="{Binding OCFabrics}"
ItemTapped="Handle_ItemTapped"
SelectedItem="{Binding SelectedItem, Mode=OneWay}"
HasUnevenRows="True"
Margin="10,10,0,0">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell Height="60">
                            <StackLayout Orientation="Horizontal">
                                <BoxView BackgroundColor="Blue" WidthRequest="10" Margin="0,0,0,10" />
                                <StackLayout BackgroundColor="White" Orientation="Vertical" Margin="5,5,10,5">
                                    <Label Text="{Binding Name}" FontAttributes="Bold" />
                                    <Label Text="{Binding Seconds, StringFormat='Seconds: {0}'}" TextColor="Gray" />
                                </StackLayout>
                            </StackLayout>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>
            </ListView>

And give it a run!

App showing the ListView populated with the items added to ObservableCollection

Yay! I can has ListView with data binding!

Let’s call it here for Part 2… Onward to Part 3 – Displaying Items in a ItemDetailsPage (coming soon!)

One thought on “Databinding a ListView – Part 2 – Writing a Xamarin.Forms App

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s