I have a simple MudDataGrid. Each row has a single MudButton in the last column:
<MudItem xs="12" sm="12" md="12">
<MudDataGrid Items="@PickList.PickListLines" Class="py-8 my-8">
<Columns>
<PropertyColumn Property="x => x.SalesOrderRef" Title="Sales Order"/>
<PropertyColumn Property="x => x.LineNumber" Title="Line"/>
<PropertyColumn Property="x => x.ProductCode" Title="Product" />
<PropertyColumn Property="x => x.Quantity" Title="Qty" />
<PropertyColumn Property="x => x.ItemType" Title="Type"/>
<TemplateColumn CellClass="d-flex justify-end">
<CellTemplate>
<MudButton Size="Size.Large" Variant="@Variant.Filled" StartIcon="@Icons.Material.Filled.DoNotDisturbOn" Color="@Color.Primary" OnClick="@(x => AddShortage(PickList.PickListId, context.Item.LineNumber))">Shortage</MudButton>
</CellTemplate>
</TemplateColumn>
</Columns>
</MudDataGrid>
</MudItem>
The OnClick handler calls a function which makes an API call. Assuming that API call completes successfully, I want to be able to change the color of the button that was clicked. I can't figure out how to reference just the one button that was clicked in a table though.... Making the call it's easy because the button has context. Not sure how that translates coming back after the call....
Any ideas?
You can either have a Color
property added to your class.
Or, use a List/Collection to store the identifier for the model when the button is clicked and get the Color
based on whether it exists or not in the List.
<MudDataGrid Items="@Elements.Take(4)">
<Columns>
<PropertyColumn Property="x => x.Number" Title="Nr" />
<PropertyColumn Property="x => x.Sign" />
<PropertyColumn Property="x => x.Name" />
<PropertyColumn Property="x => x.Position" />
<PropertyColumn Property="x => x.Molar" Title="Molar mass" />
<TemplateColumn CellClass="d-flex justify-end">
<CellTemplate>
<MudButton Color="GetColor(context.Item.Number)" Size="Size.Large" Variant="@Variant.Filled" StartIcon="@Icons.Material.Filled.DoNotDisturbOn" OnClick="@(x => AddShortage(context.Item.Position,context.Item.Number))">Shortage</MudButton>
</CellTemplate>
</TemplateColumn>
</Columns>
</MudDataGrid>
@code {
List<int> _selectedButtons = new();
Color GetColor(int itemNumber)
{
return _selectedButtons.Contains(itemNumber)? Color.Secondary: Color.Primary;
}
void AddShortage(int position,int itemNumber)
{
Console.WriteLine($"pos:{position} number:{itemNumber}");
if(_selectedButtons.Contains(itemNumber))
{
_selectedButtons.Remove(itemNumber);
}
else
{
_selectedButtons.Add(itemNumber);
}
}
private IEnumerable<Element> Elements = new List<Element>();
protected override async Task OnInitializedAsync() => Elements = await httpClient.GetFromJsonAsync<List<Element>>("webapi/periodictable");
}