dotnet / maui

.NET MAUI is the .NET Multi-platform App UI, a framework for building native device applications spanning mobile, tablet, and desktop.
https://dot.net/maui
MIT License
22.24k stars 1.76k forks source link

XAML Data Binding Error - Object reference not set to an instance of an object. #25819

Open kycuff opened 2 days ago

kycuff commented 2 days ago

Description

When trying to bind a label's text to a back end property that has a complex model I am getting this error:

"Object reference not set to an instance of an object."

An example of this can be found in the reproduction repo for the label:

<Label
    HorizontalTextAlignment="Center"
    Style="{DynamicResource TextHeadline}"
    Text="{Binding UsersData.InstalmentPlans.InstalmentPlan[0].FinancialYear}" />

Here is the data model:

public partial class UserDataViewModel : ObservableObject
{
    public UsersDataModel UsersData { get; set; }
    public UserDataViewModel()
    {
        UsersData = new UsersDataModel
        {
            InstalmentPlans = new InstalmentPlans
            {
                InstalmentPlan = new[]
                {
                    new InstalmentPlan { FinancialYear = "2023" }
                }
            }
        };
    }
}

We have successfully used the list index in other places to bind the XAML

Steps to Reproduce

Link to the reproduction link below

Link to public reproduction project repository

https://github.com/kycuff/TestApp.git

Version with bug

8.0.40 SR5

Is this a regression from previous behavior?

Not sure, did not test other versions

Last version that worked well

Unknown/Other

Affected platforms

Android

Affected platform versions

Android 13

Did you find any workaround?

Create a new field within the code behind file to retrieve UsersData.InstalmentPlans.InstalmentPlan[0].FinancialYear and bind that to the label

Relevant log output

15:57:32:097    2>        Resource: App.Routes.CouncilTax.Pages.Specific.InstalmentsPage.xaml
15:57:32:097    2>          Parsing Xaml
15:57:32:097    2>            done.
15:57:32:097    2>          Replacing 0.InitializeComponent ()
15:57:32:097    2>            failed.
15:57:32:097    2>    Routes\CouncilTax\Pages\Specific\InstalmentsPage.xaml : XamlC error : Object reference not set to an instance of an object.
IeuanWalker commented 2 days ago

This is the second time we have ran into this, with no obvious cause.

And only workaround we have so far is to create another property higher up in the model to bind to, i.e. -

public partial class InstalmentPlans
{ 
        public string LatestFinancialYear => InstalmentPlan[0].FinancialYear;
    public InstalmentPlan[] InstalmentPlan { get; set; }
}

But we have other bits of XAML accessing a similar data structure without an issue - Image

Ying-6 commented 1 day ago

This issue has been verified using Visual Studio 17.13 Preview 1(9.0.0-rc.2.24503.2 & 8.0.40 & 8.0.3 & 8.0.93). Can repro this issue.