Xamarin – binding a ListView to object

Binding

Testing how to bind a ListView to an object.

Consider a test list

public partial class testListView : ContentPage
{
    public List<string> testList { get; set; }

    public testListView ()
    {
        InitializeComponent ();

        testList = new List<string>();
        testList.Add("test");
        testList.Add("test 2")
    }
}

It’s straight-forward to set the ItemSource directly via




lstTest.ItemsSource = testList;



But if you wish to use binding instead e.g.




BindingContext = testList;



Then in the xaml use the following




<ListView x:Name="lstTest" ItemsSource="{Binding .}"></ListView>



Note the dot after the word Binding, this refers to the parent object.

Defining a template

Same thing goes when you have a template defined.

e.g.




<ListView x:Name="lstTest" ItemsSource="{Binding .}">
    <ListView.ItemTemplate>
       <DataTemplate>
            <ViewCell>



            <StackLayout Padding="5" Orientation="Horizontal" Spacing="15">



            <BoxView WidthRequest="60" HeightRequest="60" Color="RosyBrown" />



                 <StackLayout Padding="5, 0, 0, 0" VerticalOptions="Center">
                      <Label Text="{Binding .}" />
                 </StackLayout>



            </StackLayout>



           </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>



Binding to a more complex object

If there’s a list of more complex objects

The object




public class TestItem
{
    public string Title { get; set; }
    public string Description { get; set; }
    public Color Color { get; set; }
}



And the list we’re binding the page to




public List<TestItem> testList { get; set; }



Filled with some test data like so

 



 testList = new List<TestItem>
 {
     new TestItem()
     {
         Title = "test1",
         Description = "ewrwrewrewer",
         Color = Color.BlueViolet
     },
     new TestItem()
     {
        Title = "test2",
        Description = "ewrwresdf dfgdfgdfgdfgwrewer",
        Color = Color.DarkRed
     }
 };



The xaml can look like this

 



<ListView x:Name="lstTest" ItemsSource="{Binding .}" RowHeight="100">
    <ListView.ItemTemplate>
        <DataTemplate>
          <ViewCell>



          <StackLayout Padding="5" Orientation="Horizontal" Spacing="14">



          <BoxView WidthRequest="60" HeightRequest="60" Color="{Binding Color}" VerticalOptions="Start" />



          <StackLayout Padding="5, 5, 0, 0">
             <Label Text="{Binding Title}" FontAttributes="Bold" FontSize="Medium" />
             <Label Text="{Binding Description}" />
          </StackLayout>



         </StackLayout>



         </ViewCell>
       </DataTemplate>
    </ListView.ItemTemplate>
</ListView>



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.