span
span

Reputation: 5624

Using TextCell in a StackLayout in a ListView

Why can I not use a TextCell like this in a ListView item template? When I use it the rows render but they are empty.

    <ListView ItemsSource="{Binding Courses}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Vertical">
                            <TextCell Text="{Binding Title}" Detail="{Binding SubTitle}"></TextCell>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

When using a Label I can see the text contents in each row:

    <ListView ItemsSource="{Binding Courses}">
        <ListView.ItemTemplate>
            <DataTemplate>
                <ViewCell>
                    <StackLayout Orientation="Vertical">
                        <Label Text="{Binding Title}"></Label>
                        <Label Text="{Binding SubTitle}"></Label>
                    </StackLayout>
                </ViewCell>
            </DataTemplate>
        </ListView.ItemTemplate>
    </ListView>

Is there anyway I can use the TextCell inside the list item template? I am trying to build a more complext layout inside the StackLayout and it would be greatly simplified if I could re-use the Title/Detail structure of the TextCell.

Upvotes: 3

Views: 1364

Answers (2)

Ayyaz Khan
Ayyaz Khan

Reputation: 25

You Can Use Stack Layout in a text cell! Here is the way for using it.

   <TextCell>
      <TextCell.BindingContext>
         <StackLayout Orientation="Horizontal" >                      
            <Label Text="{Binding Name}"
             HorizontalOptions="CenterAndExpand" TextColor="Black"/>
            <Label Text="{Binding Description}"  
             HorizontalOptions="CenterAndExpand" TextColor="Black"/>
           <Label Text="{Binding Price}"  
            HorizontalOptions="CenterAndExpand" TextColor="Black"/>
         </StackLayout>                       
        </TextCell.BindingContext>
       </TextCell>

Upvotes: 0

sme
sme

Reputation: 4163

According to the Xamarin.Forms Cell Reference, cells are only designed to be added to ListViews or TableViews. In particular, it says:

However Cell is not a visual element, it just describes a template for creating a visual element.

So it cannot be added directly to the children of a StackLayout. You will have to create a ViewCell with a custom template for that.. You can probably look at the source code on Github to find out the proper spacing that a TextCell uses between it's Text and TextDetail labels, to keep it consistent.

Upvotes: 2

Related Questions