【问题标题】:How to change the background color of `TextCell` inside `ListView` in Xamarin Forms?如何在 Xamarin Forms 中的“ListView”中更改“TextCell”的背景颜色?
【发布时间】:2017-10-03 15:06:54
【问题描述】:

我有一个ListView 设置如下:

<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>

我有一个 iOS 渲染器并设置以下内容:

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

不知何故,我的整个ListView 正在使用我为列表视图设置的Gray 背景。我想要发生的是ListView 有一个Gray 彩色背景(这意味着标题部分将有一个灰色背景),并且TextCell 有一个Red 彩色背景。我是否设置了错误的属性来获得TextCell 所需的背景?

【问题讨论】:

    标签: c# listview xamarin.ios xamarin.forms


    【解决方案1】:

    您的自定义渲染器实际上并没有返回单元格,因此您对BackgroundColor 所做的更改没有通过。

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

    更新:您应该改为设置 cell.ContentView.BackgroundColor

    【讨论】:

    • 对不起,我错过了那部分。我直接在这里输入了示例代码。但在我的项目中,我确实返回了cell。谢谢
    • 这个答案对我没有帮助。请参考我给他的回复。谢谢。
    • 我更新了答案。你应该设置cell.ContentView.BackgroundColor。尽管不需要像其他答案中提到的那样自定义渲染器,但可能会有更好的解决方案。
    【解决方案2】:

    在 Grid/StackLayout 中添加您的文本单元并分配 BackgroundColor="Red" 直接在xaml中进行相应的布局。您不需要为此编写自定义渲染器。

    【讨论】:

    • 我相信ListViewDataTemplate 必须继承自Cell。所以我不能用StackLayout 包裹我的TextCell
    • 您可以使用 entry 代替 textcell。
    猜你喜欢
    • 2019-06-20
    • 2019-09-09
    • 1970-01-01
    • 2021-03-19
    • 2020-03-26
    • 1970-01-01
    • 2020-06-27
    • 2016-03-08
    • 1970-01-01
    相关资源
    最近更新 更多