user6742877
user6742877

Reputation:

How to change the background color of `TextCell` inside `ListView` in Xamarin Forms?

I have a ListView set up like below:

<ListView HasUnevenRows="true" BackgroundColor="Gray">
    <ListView.Header>
        <StackLayout Padding="20,35,20,10" Orientation="Horizontal" HorizontalOptions="FillAndExpand">
            <Label FontSize="13" TextColor="Gray" Text="Header text here"/>
        </StackLayout>
    </ListView.Header>
    <ListView.ItemTemplate>
        <ListView.DataTemplate>
            <TextCell Text="{Binding CategoryName}" Detail="{Binding Count}">
        </ListView.DataTemplate>
    </ListView.ItemTemplate>
</ListView>

I have a renderer for iOS and set the following:

public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
    var cell = base.GetCell(item, reusableCell, tv);
    cell.BackgroundColor = UIColor.Red;
    return cell;
}

Somehow my whole ListView is using the Gray background I set for the listview. What I want to happen is have a Gray color background for the ListView (which means the header part would have a gray background) and have Red color background for the TextCell. Am I setting the wrong property to get the desired background for TextCell?

Upvotes: 1

Views: 2874

Answers (2)

Steven Thewissen
Steven Thewissen

Reputation: 2981

Your custom renderer is not actually returning the cell, so the change you make to the BackgroundColor is not coming through.

public override UITableViewCell GetCell(Cell item, UITableViewCell reusableCell, UITableView tv)
{
    var cell = base.GetCell(item, reusableCell, tv);        
    cell.ContentView.BackgroundColor = UIColor.Red;
    return cell;
}

Update: You should be setting cell.ContentView.BackgroundColor instead.

Upvotes: 2

Renjith
Renjith

Reputation: 682

Add your textcell inside Grid/StackLayout and assign BackgroundColor="Red" for corresponding layout directly in the xaml. Your don't need to write custom renderer for that.

Upvotes: 0

Related Questions