How to change the background color of `TextCell` i

2019-07-27 06:51发布

问题:

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?

回答1:

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.



回答2:

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.