Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

XAML bindings are flagging invalid binding failures in ListView - it is confused as to what the data context is... #8433

Open
mobycorp opened this issue Jun 29, 2022 · 41 comments
Assignees
Labels
area-controls-listview ListView and TableView platform/windows 🪟 s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working
Milestone

Comments

@mobycorp
Copy link

mobycorp commented Jun 29, 2022

Description

I have a list view which has its items source set to an observable collection in a top-level view model. The collection is a list of detail view models. I have explicitly set the data context in the item template to point to the detail view model, yet the error it flags indicates it is looking at the page's data context and not the context of a single element in the list. I hate to see any binding failures, but this one will not go away...

Here is the binding error listed (there are three, actually):

Data Context	EmailsViewModel
Binding Path	Email
Target		Label.Text
Target Type	String
Description	'Email' property not found on 'MobyClient.ViewModels.EmailsViewModel', target property: 'Microsoft.Maui.Controls.Label.Text'
File			\Pages\PageEmails.xaml
Line			268

Here is the EmailsViewModel class:

namespace MobyClient.ViewModels;

public partial class EmailsViewModel : ObservableObject {

	public EmailsViewModel (IMobyLogger logger, EmailService emailService) {

		Guard.IsNotNull (logger);
		Guard.IsNotNull (emailService);

		_logger = logger;
		_emailService = emailService;
	}

	public ObservableCollection<EmailViewModel> FilteredEmails { get; set; }
	public ObservableCollection<FolderViewModel> Folders { get; set; }

	private void InitializeViewModel () {
		if (_isInitialized) return;

		_filteredEmails = new List<Email> (_emailService.Emails);

		FilteredEmails = new ObservableCollection<EmailViewModel> ();
		Folders = new ObservableCollection<FolderViewModel> (_emailService.Folders);

		_logger.LogDebug ("Emails viewmodel is initialized.");

		_isInitialized = true;
	}

	private bool _isInitialized;
	private List<Email> _filteredEmails;
	private readonly IMobyLogger _logger;
	private readonly EmailService _emailService;
}

And here is the EmailViewModel:

namespace MobyClient.ViewModels;

public partial class EmailViewModel : ObservableObject {

	[ObservableProperty]
	private Email _email;
}

Looking at the xaml used to define the list view item template:

<ListView.ItemTemplate>
	<DataTemplate>
		<ViewCell>
			<Grid
				Margin="0,1,0,0"
				Padding="3,0">
				<Grid
					x:Name="FolderItemTemplateGrid"
					x:DataType="viewModels:EmailViewModel"
					ColumnDefinitions="Auto, *, Auto"
					ColumnSpacing="5"
					Margin="10,2"
					ZIndex="1000">
					<Label
						Grid.Column="0"
						FontFamily="SegoeUiRegular"
						FontSize="14"
						Text="{Binding Email.SenderEmail.ShortDisplayName}" />
					<Label
						Grid.Column="1"
						FontFamily="SegoeUiRegular"
						FontSize="14"
						Margin="10,0,0,0"
						MaximumWidthRequest="1000"
						Text="{Binding Email.Subject}" />
					<Label
						Grid.Column="2"
						FontFamily="SegoeUiRegular"
						FontSize="14"
						Margin="10,0,0,0"
						Text="{Binding Email.MessageDate}" />
				</Grid>
			</Grid>
		</ViewCell>
	</DataTemplate>
</ListView.ItemTemplate>

I am clearly setting the datatype for the item template to be of the EMAIL view model and NOT the EMAILS view model! Trust me when I say that the Email class DOES have the properties, SenderEmail.ShortName (from an EmailAddress class), Email.Subject, and Email.Message date.

So, why is the error pointing to the EmailsViewModel when I have set the datatype to be EmailViewModel? Intellisense works (which to my understanding is driven by the x:DataType property... I don't get it!

My code base has grown to a size where it is not feasible to give you a github repository, so the code snippets above will have to work.

Steps to Reproduce

I know you won't like this, but you will need to generate a simple app that has a listview with an itemtemplate defined as I listed above.

I can see no reason why these binding errors are being flagged....

Version with bug

6.0.400 (current)

Last version that worked well

Unknown/Other

Affected platforms

Windows, I was not able test on other platforms

Affected platform versions

net6.0-windows10.0.19041.0

Did you find any workaround?

No...

Relevant log output

No response

@mobycorp mobycorp added s/needs-verification Indicates that this issue needs initial verification before further triage will happen t/bug Something isn't working labels Jun 29, 2022
@rachelkang
Copy link
Member

Hi, @mobycorp - Thank you for opening this issue. I understand that you may not be able to share your project, but would you be able to share a sample (in the form of a GitHub repository) that reproduces the issue you describe? That would help us tremendously in investigating this further and helping to debug this issue.

@rachelkang rachelkang added s/needs-info Issue needs more info from the author and removed s/needs-verification Indicates that this issue needs initial verification before further triage will happen labels Jun 30, 2022
@ghost
Copy link

ghost commented Jun 30, 2022

Hi @mobycorp. We have added the "s/needs-info" label to this issue, which indicates that we have an open question for you before we can take further action. This issue will be closed automatically in 7 days if we do not hear back from you by then - please feel free to re-open it if you come back to this issue after that time.

@mobycorp
Copy link
Author

I am currently on a severe deadline and barely have time to eat dinner, so, no. I cannot supply you with example code. I indicated as much from above. You guys are smart guys and should have no problem reproducing what I have reported.

@ghost ghost added s/needs-attention Issue has more information and needs another look and removed s/needs-info Issue needs more info from the author labels Jun 30, 2022
@StephaneDelcroix
Copy link
Contributor

@mobycorp

  • do you get that error at runtime or compile time
  • running in DEBUG or RELEASE. does it happens on both ?
  • how are you setting your list view item source
  • are you sure EmailViewModel has a public Email property ?

We tried to come up with a repro, based on the scarce info you gave us, but that repro is working well. I'm sorry about your severe deadlines, and the impact on your work-life balance. We understand the sense of urgency, and this is why you got quick answers. If you really need this investigated, you definitely have to provide the smallest possible project that triggers this behaviour, and we will look at it. Thanks

@jfversluis jfversluis added s/needs-repro Attach a solution or code which reproduces the issue and removed s/needs-attention Issue has more information and needs another look labels Jun 30, 2022
@ghost
Copy link

ghost commented Jun 30, 2022

Hi @mobycorp. We have added the "s/needs-repro" label to this issue, which indicates that we require steps and sample code to reproduce the issue before we can take further action. Please try to create a minimal sample project/solution or code samples which reproduce the issue, ideally as a GitHub repo that we can clone. See more details about creating repros here: https://github.com/dotnet/maui/blob/main/.github/repro.md

This issue will be closed automatically in 7 days if we do not hear back from you by then - please feel free to re-open it if you come back to this issue after that time.

jfversluis added a commit to jfversluis/Repro8433 that referenced this issue Jun 30, 2022
@mobycorp
Copy link
Author

mobycorp commented Jun 30, 2022

Untitled

I'm not trying to be difficult. I am on a tight deadline... And, Gerald, love your YouTube channel!! :-)

The errors are triggered by the display of content in the listview in the picture. One per row x3 because there are three properties in the view model. I tried dereferencing the three properties so that:

<Grid
	x:Name="FolderItemTemplateGrid"
	ColumnDefinitions="Auto, *, Auto"
	ColumnSpacing="5"
	Margin="10,2"
	ZIndex="1000">
	<Label
		Grid.Column="0"
		FontFamily="SegoeUiRegular"
		FontSize="14"
		Text="{Binding Email.SenderEmail.ShortDisplayName}" />
	<Label
		Grid.Column="1"
		FontFamily="SegoeUiRegular"
		FontSize="14"
		Margin="10,0,0,0"
		MaximumWidthRequest="1000"
		Text="{Binding Email.Subject}" />
	<Label
		Grid.Column="2"
		FontFamily="SegoeUiRegular"
		FontSize="14"
		Margin="10,0,0,0"
		Text="{Binding Email.MessageDate}" />
</Grid>

becomes:

<Grid
	x:Name="FolderItemTemplateGrid"
	ColumnDefinitions="Auto, *, Auto"
	ColumnSpacing="5"
	Margin="10,2"
	ZIndex="1000">
	<Label
		Grid.Column="0"
		FontFamily="SegoeUiRegular"
		FontSize="14"
		Text="{Binding ShortDisplayName}" />
	<Label
		Grid.Column="1"
		FontFamily="SegoeUiRegular"
		FontSize="14"
		Margin="10,0,0,0"
		MaximumWidthRequest="1000"
		Text="{Binding Subject}" />
	<Label
		Grid.Column="2"
		FontFamily="SegoeUiRegular"
		FontSize="14"
		Margin="10,0,0,0"
		Text="{Binding MessageDate}" />
</Grid>

but this did not change anything. The errors are still being generated...

@jfversluis, since I you didn't post the xaml you used to generate your example picture, I am not sure if you are doing things exactly like me. Did you create an item template that looks similar to the above. I know that HotReload NEVER works when I makes changes to code in a template and I am wondering if it is because of the item template... ???

This is my entire listview definition:

<ListView
	ItemsSource="{Binding FilteredEmails}"
	SelectionMode="Single">
	<ListView.ItemTemplate>
		<DataTemplate
			x:DataType="viewModels:EmailViewModel">
			<ViewCell>
				<Grid
					Margin="0,1,0,0"
					Padding="3,0">
					<Grid.GestureRecognizers>
						<TapGestureRecognizer
							Command="{Binding EmailSelectedCommand, Source={RelativeSource AncestorType={x:Type viewModels:EmailsViewModel}}}"
							CommandParameter="{Binding}" />
					</Grid.GestureRecognizers>
					<Rectangle
						BackgroundColor="{StaticResource Gray100}"
						Stroke="Gray"
						StrokeThickness="1"
						ZIndex="1" />
					<Grid
						x:Name="FolderItemTemplateGrid"
						ColumnDefinitions="Auto, *, Auto"
						ColumnSpacing="5"
						Margin="10,2"
						ZIndex="1000">
						<Label
							Grid.Column="0"
							FontFamily="SegoeUiRegular"
							FontSize="14"
							Text="{Binding Email.SenderEmail.ShortDisplayName}" />
						<Label
							Grid.Column="1"
							FontFamily="SegoeUiRegular"
							FontSize="14"
							Margin="10,0,0,0"
							MaximumWidthRequest="1000"
							Text="{Binding Email.Subject}" />
						<Label
							Grid.Column="2"
							FontFamily="SegoeUiRegular"
							FontSize="14"
							Margin="10,0,0,0"
							Text="{Binding Email.MessageDate}" />
					</Grid>
				</Grid>
			</ViewCell>
		</DataTemplate>
	</ListView.ItemTemplate>
</ListView>

There are two things to note here:

  1. The tap gesture works so it knew enough to dereference the relative sourcing to the gesture handler
  2. You can see that I declare the datatype at the DataTemplate level: x:DataType="viewModels:EmailViewModel" I know this works because intellisense was able to find all of the properties after I typed Email 'dot' field name (even the Email 'dot' SenderEmail 'dot'

Does any of that make sense?

@ghost ghost added s/needs-attention Issue has more information and needs another look and removed s/needs-repro Attach a solution or code which reproduces the issue labels Jun 30, 2022
@jfversluis
Copy link
Member

Thanks for the kind words, appreciate it! 😄

The XAML I used is in that sample repo I posted. I didn't link it up the right way here, but you should be able to see my full reproduction here: https://github.com/jfversluis/Repro8433 for the bits and pieces you posted that is what it boiled down to according to me.

The thing that stands out in your opening post, is that the error states it's looking for the Email property on the EmailsViewModel notice the plural in this case. This is also reflected in your screenshot you posted in your last message. So it seems like something is mixed up in the scopes of things.

While reviewing your code I think I see what's up... Maybe. I see you set the x:DataType on the DataTemplate I vaguely recall doing that one time and it not working. Could you move that down to the ViewCell or the Grid maybe? Does that change it?

@jfversluis jfversluis added s/needs-info Issue needs more info from the author and removed s/needs-attention Issue has more information and needs another look labels Jun 30, 2022
@ghost
Copy link

ghost commented Jun 30, 2022

Hi @mobycorp. We have added the "s/needs-info" label to this issue, which indicates that we have an open question for you before we can take further action. This issue will be closed automatically in 7 days if we do not hear back from you by then - please feel free to re-open it if you come back to this issue after that time.

@mobycorp
Copy link
Author

@jfversluis You picked up on the exact issue that I am trying to describe.

  1. The data context for the page is the EmailsViewModel (again, you noticed correctly it is the plural view model - the master if you will)
  2. I explicitly set the data context for the item template by stating x:DataType="viewModels:EmailViewModel" (not plural - the detail view model)
  3. I looked at your repo and the way you defined both view models looks correct.

Unless I don't understand fully what the x:DataType declaration does, I would think that would allow the parser to correctly map the properties in the detail view model (EmailViewModel)

@ghost ghost added s/needs-attention Issue has more information and needs another look and removed s/needs-info Issue needs more info from the author labels Jun 30, 2022
@mobycorp
Copy link
Author

@jfversluis Some additional detail... This is the code-behind of the content page:

namespace MobyClient.Pages;
public partial class PageEmails : ContentPage {
	public PageEmails (EmailsViewModel emailsViewModel) {
		Guard.IsNotNull (emailsViewModel);
		InitializeComponent ();
		BindingContext = emailsViewModel;
	}
}

@mobycorp
Copy link
Author

@mobycorp

  • do you get that error at runtime or compile time
  • running in DEBUG or RELEASE. does it happens on both ?
  • how are you setting your list view item source
  • are you sure EmailViewModel has a public Email property ?

We tried to come up with a repro, based on the scarce info you gave us, but that repro is working well. I'm sorry about your severe deadlines, and the impact on your work-life balance. We understand the sense of urgency, and this is why you got quick answers. If you really need this investigated, you definitely have to provide the smallest possible project that triggers this behaviour, and we will look at it. Thanks

Here are the answers to your questions:

  1. Runtime
  2. Debug
  3. I supplied code for the code-behind of the content page in a reply to Gerald below which is for EmailsViewModel (notice the plural of Emails - this is the master viewmodel) as the binding context
  4. Yes, EmailViewModel (the detail viewmodel) has a public property Email

@mobycorp
Copy link
Author

x:DataType is a compiled binding, it does not set the BindingContext, it should work even removing it.

What that does is to resolve the binding expressions at compile-time rather than runtime speeding up the binding process and also allows the intellisense in the xaml editor to suggest the properties for you reporting build errors when invalid properties are found.

Ok, that is exactly what I supposed x:DataType did. So, when in the xaml editor and I type Email.Subject and no squiggly lines are there AND it was able to find the properties and properties of properties, I would expect it to NOT report binding errors. That is the basic crux of what I am reporting.

@PentaTech
Copy link

PentaTech commented Jun 30, 2022

If you remove the DataType in the ItemTemplate it will force the DataType you probably defined in your ContentPage expecting to find "Email" in EmailsViewModel, with "classic bindings" you should remove that too

Anyway the error shouldn't allow you to compile so that seems a bit different from what is happening to you...

As Gerald said, probably there's something about setting the DataType to the DataTemplate that gives you those errors at runtime

@jsuarezruiz jsuarezruiz added the area-xaml XAML, CSS, Triggers, Behaviors label Jul 1, 2022
@willshoemaker
Copy link

willshoemaker commented Jul 6, 2022

I am experiencing the same issue and have created a repro here:
https://github.com/willshoemaker/MauiRepro8433

If the collection property on the view model is set prior to setting the view model as the binding context I do not experience a binding error, but if I set the value of the collection property later (in this case via a delayed Loaded event handler) there are binding errors for each property on each item in the collection. Note that despite the binding errors it appears to be displaying correctly, though it does not respond to XAML hot reload. I have only tested the issue on the Windows platform.

These errors occur both when the content of the ViewCell is in the initial page and also when it is in a separate ContentView

@samhouts samhouts added this to the .NET 8 + Servicing milestone Sep 12, 2023
@samhouts samhouts changed the title XAML bindings are flagging invalid binding failures - it is confused as to what the data context is... XAML bindings are flagging invalid binding failures in ListView - it is confused as to what the data context is... Sep 12, 2023
@DOsterholz
Copy link

I have the same problem here. My bindings work as expected, but the xaml compiler throws me error messages. However, I can launch and use the application as expected. The problem occurs in the ListView for me.

@samhouts samhouts added the p/1 Work that is important, and has been scheduled for release in this or an upcoming sprint label Sep 18, 2023
@crazyfox55
Copy link

I have this issue after I upgraded from .Net 7 to .Net 8 as well as the responsiveness of opening my page is much slower.

@DominikErnst
Copy link

Any news about the Problem?

@StephaneDelcroix StephaneDelcroix self-assigned this Mar 28, 2024
@StephaneDelcroix
Copy link
Contributor

I am experiencing the same issue and have created a repro here: https://github.com/willshoemaker/MauiRepro8433

If the collection property on the view model is set prior to setting the view model as the binding context I do not experience a binding error, but if I set the value of the collection property later (in this case via a delayed Loaded event handler) there are binding errors for each property on each item in the collection. Note that despite the binding errors it appears to be displaying correctly, though it does not respond to XAML hot reload. I have only tested the issue on the Windows platform.

These errors occur both when the content of the ViewCell is in the initial page and also when it is in a separate ContentView

if you set the ItemsSource late, those Bindings Errors are normal, and expected, and should not prevent the proper display of the page.

I believe there's no problem here, the error are genuine at the time they're produced. I'm closing this old bug, if you have an issue that affects the rendering of the page, please open a new issue

@ransagy
Copy link

ransagy commented Mar 28, 2024

How exactly is it normal and expected to get errors and break hot reload everytime you want to refresh your binding? Is it not allowed to set the ItemSource late? is it documented as such?

I don't see how this issue is resolved in any way.

@StephaneDelcroix
Copy link
Contributor

StephaneDelcroix commented Mar 28, 2024

Bindings Errors aren't crashing the app, are they ? They only show up in the log window, as a diagnostic. It is normal to see them if you set your context late, cause at the time, there's indeed an error

But if you say HotReload breaks, there's indeed something to act on, and I'm reopenening this

/cc @chabiss

@spadapet
Copy link
Contributor

@StephaneDelcroix the binding failures are not caused by the app setting the binding context late. The ListView is set up properly, but something internal to MAUI seems to be setting the binding context late for each item. It's out of the developer's control.

See my comment with a screenshot in this bug:

This shouldn't affect hot reload though, so maybe something else is going on with hot reload.

@jeroen-corteville
Copy link

@StephaneDelcroix Hi, I think you can find more information here: #5511 (comment)

@samhouts samhouts removed the p/1 Work that is important, and has been scheduled for release in this or an upcoming sprint label Apr 23, 2024
@ajsuydam
Copy link

@StephaneDelcroix @samhouts I'm going to add my voice to the others here - when I'm using list views, I constantly get binding errors in the log, even though it shows properly, and Hot Reload is touch and go under these circumstances. This is a serious issue for my project.

@PureWeen PureWeen modified the milestones: .NET 8 + Servicing, Backlog Aug 2, 2024
@MarcelWolterbeek
Copy link

Workaround to prevent the warnings (and InvalidCastExceptions):
In your ViewCell implementation add this code:

protected override void OnBindingContextChanged()
{
    if (BindingContext is TheViewModelForYourListItem)
        base.OnBindingContextChanged();
}

@jo-ruch
Copy link

jo-ruch commented Nov 5, 2024

Here is a generic solution to apply @MarcelWolterbeek 's solution

CustomViewCell.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ViewCell 
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml">
</ViewCell>

CustomViewCell.xaml.cs

namespace Your.Namespace.Here
{
    public partial class CustomViewCell<T> : ViewCell
    {
        protected override void OnBindingContextChanged()
        {
            if (BindingContext is T)
            {
                base.OnBindingContextChanged();
            }
        }
    }
}

Then this can be used as:

...

<ListView>
   <ListView.ItemTemplate>
        <DataTemplate>
            <ns:CustomViewCell x:TypeArguments="viewModels:ViewModelThatShouldBeUsed">
                 ....
             </ns:CustomViewCell>
        <DataTemplate>
   <ListView.ItemTemplate>
<ListView>

@FireController1847
Copy link

Adding a +1 to this issue. The spam of warnings becomes quite unbearable when you have a list with a few hundred objects in it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-controls-listview ListView and TableView platform/windows 🪟 s/triaged Issue has been reviewed s/verified Verified / Reproducible Issue ready for Engineering Triage t/bug Something isn't working
Projects
None yet
Development

No branches or pull requests