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

MAUI中ListView用Label触发空引用异常,TextCell却可正常工作

MAUI ListView使用Label在DataTemplate中触发NullReferenceException问题

我开发了一个简易MVVM架构的MAUI应用,尝试在ListView的DataTemplate内使用Label控件绑定字符串类型的Label属性,代码如下:

<ListView
    ItemsSource="{Binding MenuItems}"
    SelectedItem="{Binding SelectedMenuItem}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding Label}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

启动应用时会抛出NullReferenceException,即使不使用数据绑定,直接设置Label的Text为固定文本,仍会触发该异常:

<ListView.ItemTemplate>
    <DataTemplate>
        <Label Text="SomeText" />
    </DataTemplate>
</ListView.ItemTemplate>

但将Label替换为TextCell后,应用可正常启动且绑定功能正常,代码如下:

<ListView
    ItemsSource="{Binding MenuItems}"
    SelectedItem="{Binding SelectedMenuItem}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Label}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

问题原因与解决方法

MAUI的ListView.ItemTemplate要求其根元素必须是Cell派生类(如TextCell、ViewCell等)。直接使用Label这类非Cell控件时,MAUI内部在渲染列表项时无法找到正确的Cell容器,进而抛出NullReferenceException。

TextCell本身就是Cell的子类,所以可以直接在DataTemplate中使用;而Label需要包裹在ViewCell中,让ListView能够正确识别和渲染列表项,修改后的代码如下:

<ListView
    ItemsSource="{Binding MenuItems}"
    SelectedItem="{Binding SelectedMenuItem}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Label}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

内容的提问来源于stack exchange,提问作者Nowayout

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 17:55:02