0
votes

I am creating a ListView whose items I want to directly control with code. I have the following xaml that declares a generic ListView.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:ViewCellClick"
             x:Class="ViewCellClick.MainPage">
    <ListView x:Name="___listview" HasUnevenRows="True">
        <ListView.ItemTemplate>
        </ListView.ItemTemplate>
    </ListView>
</ContentPage>

and then in the code behind, I set up the ItemsSource property.

namespace ViewCellClick
{
    public partial class MainPage : ContentPage
    {
        public MainPage()
        {
            InitializeComponent();
            ___listview.ItemsSource = Repository.GetList();
            ___listview.ItemTemplate = new DataTemplate(typeof(CustomViewCell));
        }
    }

and this leverages a custom template defined as...

    public class CustomViewCell : ViewCell
    {
        public CustomViewCell()
        {
            var stack = new StackLayout();

            stack.Children.Add(new Label() { Text = "Label" });

            // HOW DO I ACCESS THE MODEL HERE SO I CAN DRAW CUSTOM UI DEPENDING ON THE MODEL INSTANCE?

            View = stack;
        }
    }
}

at this level, I have a very generic custom view cell as it only creates a label. However, say the model is complicated, and depending on the data in the model I would draw a different UI for that ViewCell instance.

How do I get access to the model for each CustomViewCell and then draw the UI according to that model?

I tried BindingContext, but it's null in the CustomViewCell constructor.

enter image description here

1

1 Answers

1
votes

The BindingContext of thew ViewCell will have a reference to the current item in the list. You will need to cast it to the appropriate type in order to use it.