Search code examples
c#xamlmaui

MAUI Label data binding raises NullReferenceException but TextCell works


I have a pretty simple MVVM App, inside DataTemplate of a ListView, there is a Label control binds to my Label property (a string).

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

When I starts the app, a NullReferenceException is throw:

Screen shot of the exception

Even if I don't use any binding, the app still throws NullReferenceException:

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

But if I use TextCell to replace Label, everything is fine: the app starts and the binding is working.

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

Solution

  • DataTemplates in a ListView should always use a Cell, so the NullReferenceException you're seeing has nothing to do with the Label or it's binding probably.

    Change your code to this:

    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Label Text="{Binding Label}" />
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>