You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin中修改ListView文字颜色后出现异常叠加文本问题

解决Xamarin.Forms ListView TextCell文本叠加问题

看起来你遇到的文本叠加问题,核心原因是绑定路径设置错误,结合TextCell的默认渲染逻辑导致了异常。咱们一步步来修复:

问题分析

你后台绑定的是List<string>,这意味着ListView的每个列表项的BindingContext就是单个字符串对象。但你在TextCell里写了Text="{Binding names}"——字符串对象并没有names这个属性,这会导致绑定失效,而TextCell的默认渲染逻辑可能同时显示了绑定错误的占位内容和项本身的字符串值,最终造成文本叠加的情况。

解决方案

把TextCell的Text绑定改成直接绑定当前的BindingContext(也就是字符串本身),有两种等效写法:

修正后的XAML代码

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="RoseySports.Invite_Page">
<ContentPage.Content>
<AbsoluteLayout VerticalOptions="FillAndExpand" HorizontalOptions="FillAndExpand">
<Image AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0, 0, 1, 1" Source="background.jpg" Aspect="AspectFill"/>
<ScrollView AbsoluteLayout.LayoutFlags="All" AbsoluteLayout.LayoutBounds="0, 0, 1, 1">
<ContentView Padding="10, 40, 10, 10">
<ListView x:Name="inviteesp" SeparatorColor="White" BackgroundColor="Transparent" Header="People">
<ListView.ItemTemplate>
<DataTemplate>
<!-- 修正绑定路径,直接绑定当前字符串项 -->
<TextCell Text="{Binding .}" TextColor="White"/>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</ContentView>
</ScrollView>
</AbsoluteLayout>
</ContentPage.Content>
</ContentPage>

也可以把{Binding .}简写为{Binding},效果完全一致。

为什么这样有效?

当ItemsSource是List<string>时,每个列表项的BindingContext就是一个独立的string值。{Binding .}会直接绑定这个字符串本身,让TextCell正确显示名字,同时避免了绑定错误带来的异常渲染。

额外优化(可选)

如果之后你需要绑定更复杂的自定义对象(比如Person类),可以再改成Text="{Binding Name}"这类指定属性的写法;如果还是遇到平台特定的渲染问题,也可以用ViewCell替代TextCell,手动添加Label来更灵活控制样式:

<DataTemplate>
<ViewCell>
<Label Text="{Binding .}" TextColor="White" Padding="10,15"/>
</ViewCell>
</DataTemplate>

后台代码验证

你的C#后台代码是完全没问题的,不需要修改:

using System;
using System.Collections.Generic;
using Xamarin.Forms;

namespace RoseySports
{
    public partial class Invite_Page : ContentPage
    {
        public Invite_Page()
        {
            InitializeComponent();
            var names = new List<String> { "Mohamed Al-Sabbagh", "Adrien Tardy" };
            inviteesp.ItemsSource = names;
        }
    }
}

这样修改后,应该就能解决文本叠加的问题,正确显示白色的名字列表了。

内容的提问来源于stack exchange,提问作者Mohamed Al Sabbagh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 09:27:47