I am using a MudDataGrid
with a HierarchyColumn
to selectively display the ChildRowContent
on any row of my data grid. So far, everything works great. Initially, all rows are collapsed.
When some of the rows are extended / visible, and I reload the underlying data set / list, all rows are collapsed again.
What I would like to do is to track the expansion status of each ChildRowContent
so the user does not have to manually expand the respective rows he/she was working on.
I know there is InitiallyExpandedFunc
on HierarchyColumns
, which gives me at the option to initially expand specific rows, but in order to use this, I need to track the visibility of each row's ChildRowContent
.
Minimum Example:
<MudDataGrid Items="@_elements">
<Columns>
<HierarchyColumn T="string" InitiallyExpandedFunc="@(x => _isRowExpanded[x])"/>
<PropertyColumn Property="x => x" />
</Columns>
<ChildRowContent>
Child row content of example
</ChildRowContent>
</MudDataGrid>
@code {
private IEnumerable<string> _elements = new List<string>() { "Bird", "Cat", "Dog"};
private Dictionary<string, bool> _isRowExpanded = new();
protected override void OnInitialized()
{
_isRowExpanded.Add("Cat", true);
}
// how to hook up this function when a child column is expanded???
private void SetExpansionStatus(string value, bool isExpanded)
{
_isRowExpanded[value] = isExpanded;
}
}
And since we are already here - is there a way to programmatically expand a row? If so, I would like to connect that with the RowClick
function of the MudDataGrid
, as it would feel more intuitive in my scenario.
Based on your code I made a workaround as following without using HierarchyColumn but grant more control over the content.
@page "/"
<style>
.mud-table-child-content {
padding: 0 !important
}
</style>
<MudButton Variant="Variant.Filled" Color="Color.Primary" OnClick="ReloadData" Class="my-2">
Reload Data
</MudButton>
<MudDataGrid T="string" Items="@_elements" RowClick="OnRowClick">
<Columns>
<PropertyColumn Property="x => x" />
</Columns>
<ChildRowContent>
@if (Expands.Contains(context.Item))
{
<div style="padding:20px">
Child row content of example
</div>
}
</ChildRowContent>
</MudDataGrid>
@code {
private List<string> _elements = new List<string>() { "Bird", "Cat", "Dog" };
private List<string> Expands = new List<string>();
protected override void OnInitialized()
{
Expands.Add("Bird");
}
private void OnRowClick(DataGridRowClickEventArgs<string> args)
{
if (Expands.Contains(args.Item))
{
Expands.Remove(args.Item);
}
else
{
Expands.Add(args.Item);
}
}
private async Task ReloadData()
{
_elements.Add("Cow");
StateHasChanged(); // Refresh UI after reloading
}
}
···