[DataGrid]: using RowDetailsTemplate sets wrong DataContext
See original GitHub issueDescribe the bug
Hello,
When using a RowDetailsTemplate of a DataGrid, the RowDetailsTemplate will have the parent DataContext set, which causes a crash.
To Reproduce
- Create a list of items
- Assign to a DataGrid
- Launch => the items are displayed.
- Add a RowDetailsTemplate that display some property
- Launch => crash
The issue also happens if there is no item in the list.
(example project included)
Expected behavior
The RowDetailsTemplate DataContext should be the Item and not the parent. If the list is empty RowDetailsTemplate should not be called since there is no item.
Example Project
In the example project if you launch with the RowDetailsTemplate commented no problem.
But if you uncomment the RowDetailsTemplate you will get a crash because the wrong data context was set:
Unable to cast object of type 'DataGridBug.ViewModels.ItemListViewModel' to type 'DataGridBug.ViewModels.ItemViewModel'.
Even worse if you use the ContentControl instead of the TextBlock it will recursively show the wrong View causing a StackOverFlow.
Informations
- Avalonia Version 11.0.0
Edit: updated post
Issue Analytics
- State:
- Created 2 months ago
- Comments:6 (2 by maintainers)
Top GitHub Comments
Hello,
I spent some time digging in the Avalonia Source code today and i think i found the issue and how to to fix it.
First i reproduced the issue in the ControlCatalog.
i Added a RowDetailsTemplate to the first Tab in the DataGridPage.
DataGridPage.xaml
then i removed the ItemsSource assignation to set an empty list
DataGridPage.xaml.cs line 39
Now when launching and going to the DataGridPage we are getting the StackOverflow instead of getting an empty DataGrid.
After some debuging and digging, i found out that the problems comes from here
https://github.com/AvaloniaUI/Avalonia/blob/194044692eb3967b8c6bd0ed140a954f53b48e0e/src/Avalonia.Controls.DataGrid/DataGridRows.cs#L2973-L2976
In our case the dataItem is null, but the
detailsContent.DataContext
is set toControlCatalog.Pages.DataGridPage
so when it enters the function bellow
detailsContent.Measure
i think it’s measuring the wrong stuff and goes on a recursive loop.If i comment the check the problem is solved.
Now if i relaunch the ControlCatalog and go to the DataGridPage:
ControlCatalog.Models.Country
like it should.ControlCatalog.Models.Country
for every item.So:
I didn’t investigate further in the underlying function, so maybe i’m wrong and/or there is another deeper issue.
I hope it helps. Thanks.
Done https://github.com/AvaloniaUI/Avalonia/pull/12174