I have a parent and a child component in Blazor. Is there an easier way to both bind-Value between parent-child and also run code in parent if bind-value changed?
I have this code
Parent:
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
<Test @bind-BitValue="MyValue" BitValueChangedCallback="HandleMyValueChanged"/>
Welcome to your new app.
<br />
MyValue : <span>@MyValue</span> <br />
MyTValue : <span>@MyTValue</span>
@code {
public int MyValue { get; set; }
public int MyTValue { get; set; } = 0;
private void HandleMyValueChanged (int newValue)
{
MyTValue = newValue * 2;
}
}
And Child "Test.razor" :
<h3>Test</h3>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
[Parameter]
public int BitValue { get; set; }
[Parameter]
public EventCallback<int> BitValueChanged { get; set; }
[Parameter]
public EventCallback<int> BitValueChangedCallback { get; set; }
private async Task IncrementCount()
{
BitValue++;
await BitValueChanged.InvokeAsync(BitValue);
await BitValueChangedCallback.InvokeAsync(BitValue);
}
}
As you can see I have 2 InvokeAsync in child, one that are linked to Value and one that trigger a method in parent. Are there a better way to solve this?
You could try use
@bind-BitValue:afterto bind event to a method: