[Blazor] Migrating property from one-way to two way binding #49187
-
Hi, I need to rewrite quite a bit of existing code to implement two-way binding for
Which is the proper (clean) approach? I'm currently on .NET 6 but I know that you have been adding new features with respect to binding. If I choose option 1 (more convenient) what are the repercussions of discarding the I want to use the best approach assuming that I will take advantage of all new features available in .NET 7 and upcoming .NET 8. Thank you for your help! [Parameter]
public int ActivePageIndex
{
get => m_activePageIndex;
set
{
if (m_activePageIndex != value)
{
m_activePageIndex = value;
_= ActivePageIndexChanged.InvokeAsync(value);
}
}
}
[Parameter]
public EventCallback<int> ActivePageIndexChanged { get; set; } protected async Task DeleteItem(MouseEventArgs mouseEventArgs, TItem item)
{
// ...
ActivePageIndex--;
// if not using setter, invoke binding this way
await ActivePageIndexChanged.InvokeAsync(ActivePageIndex);
} |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I recommend not use two way binding in blazor, instead use javascript to ask the browser what the current value is, on demand. It avoids the browser talking to .NET too much, honestly speaking |
Beta Was this translation helpful? Give feedback.
-
That is almost what I'd recommend, except you shouldn't directly call the setter of an incoming Instead the way you modify your "ActivePageIndex" should be exclusively by calling |
Beta Was this translation helpful? Give feedback.
That is almost what I'd recommend, except you shouldn't directly call the setter of an incoming
[Parameter]
property. See https://learn.microsoft.com/en-us/aspnet/core/blazor/components/overwriting-parameters?view=aspnetcore-7.0Instead the way you modify your "ActivePageIndex" should be exclusively by calling
ActivePageIndexChanged.InvokeAsync(newValue)
, then the parent component that uses@bind-ActivePageIndex
will receive the new value, re-render itself, and in turn cause your child component to be re-rendered with the newActivePageIndex
.