Search code examples
c#listviewxamarinxamarin.formsdatatemplate

Xamarin Forms ListView ItemsSource issue


I have a ListView and its ItemsSource.

ListView IList = new ListView();
IList.ItemsSource = _routine_names; 

In order to customize the Data Template for each item I'm doing:

IList.ItemTemplate = new DataTemplate(()=>
        {
            Label Routine_Name = new Label(); // should be_routine_names
            return new ViewCell
            {
                View = new StackLayout{
                    Children = {Routine_Name}
                }
            };
        });

When I run this my ListView is displayed and the list items are indeed there (they have onclick handlers that work) but there is no text, which should be whatever is in _routine_names.

My question how do I get the Label in the DataTemplate to be items in _routine_names?

The reason I'm adding a DataTemplate is so I can add swipe to delete.


Solution

  • You can just use the built in TextCell for what you're trying to do. It has a bindable TextProperty and an optional DetailProperty if you want a smaller text line below the main one.

    IList.ItempTemplate = new DataTemplate(()=> 
    {
        var textCell = new TextCell();
        textCell.ContextActions.Add(yourAction);
        textCell.SetBinding(TextCell.TextProperty, "."); 
        return textCell; 
    }
    
    IList.ItemsSource = _routine_names; 
    

    yourAction is of type MenuItem as seen here

    Also, please notice that IList is a name of a class in System.Collection namespace so I'd use something else there.