【发布时间】:2021-07-29 18:35:39
【问题描述】:
是否可以在 Blazor 子组件中双向绑定集合?
TLDR;当执行ValueChangedEventCallBack 处理程序时,对象中的列表类型属性设置为null,这会抛出NullReferenceExceptions,因为它在页面中设置为null。
我有以下例子:
public class Person
{
public string FullName { get; set; }
public List<string> NickNames { get; set; } = new List<string>();
}
首页:Index.razor
<h1>@Mario.FullName - @string.join('-', Mario.NickNames)</h1>
<NicknamesListComponent @bind-Nicknames="Mario.NickNames" />
@code{
public Person Mario { get; set; } =
new Person() { FullName = "Mario", NickNames = new List<string> {"Super", "Mama" , "Mia"} }
}
子组件:NicknamesListComponent.razor
<ul>
@for(int i = 0; i < Nicknames.Count; i++)
{
@var index = i;
<li>
@Nicknames[index]
<a @onclick="() => RemoveNickname(index)">Remove</a>
</li>
}
</ul>
@code {
[Parameter]
public List<string> Nicknames { get; set; }
[Parameter]
public EventCallback<List<string>> NicknamesChanged { get; set; }
public async Task RemoveNickname(int index)
{
Nicknames.RemoveAt(index);
//////////////////////////////////////////////////////////
// When executing NicknamesChanged. the User.Nicknames property is completly cleared and
// set to NULL... this throws exceptions everywhere in the index.blazor
await NicknamesChanged.InvokeAsync();
}
}
如果我删除了NicknamesChanged,那么带有删除按钮的列表就可以工作了...但是这次父母不会收到更改通知并且昵称保持不变...
【问题讨论】:
标签: c# .net asp.net-core frontend blazor