为什么在blazor模板中值不更新?



我正在处理一个自定义网格组件,并且在网格的每一行中我都有一个复选框。复选框的状态将决定该行的css类。

Index.razor:

<Test Items="Transactions">
<TestBody Context="row">
<TestCell Row=row></TestCell>
</TestBody>
</Test>

Test.razor:

@typeparam TItem
@attribute [CascadingTypeParameter(nameof(TItem))];
<CascadingValue Value="this" IsFixed="true">
<table>
<tbody>
@foreach (var row in Rows)
{
<tr @key="row">
@TestBody(row)
<span>@row.Checked</span>   // .. this does not get updated
</tr>
}
</tbody>
</table>
</CascadingValue>

Test.razor.cs:

namespace Accounting.Web.Components.Test
{
public class TestRow<TItem>
{
public TItem Item { get; set; } = default!;
public int Id { get; set; } = default!;
public bool Checked = false;
}
public partial class Test<TItem>
{
[Parameter]
public IList<TItem> Items { get; set; } = default!;
[Parameter]
public RenderFragment<TestRow<TItem>> TestBody { get; set; } = default!;
public List<TestRow<TItem>> Rows { get; set; } = new();
protected override void OnInitialized()
{
int i = 1;
foreach (var item in Items)
{
var gridRow = new TestRow<TItem>()
{
Id = i,
Item = item,
};
Rows.Add(gridRow);
i++;
}
}
}
}

TestCell.razor:

@typeparam TItem
<input type="checkbox" @onchange="eventArgs => { OnCheckChanged(eventArgs.Value); }" />

TestCell.razor.cs:
namespace Accounting.Web.Components.Test
{
public partial class TestCell<TItem>
{
[Parameter]
public TestRow<TItem> Row { get; set; } = default!;
[Parameter]
public RenderFragment ChildContent { get; set; } = default!;
public void OnCheckChanged(object checkedValue)
{
System.Console.WriteLine((bool)checkedValue); // this reflects the correct state of the checkbox
Row.Checked = (bool)checkedValue;
StateHasChanged();
}
}
}

问题是当复选框状态改变时,改变行状态(作为参数传递给TestCell.razor)不会触发行值的改变。已检查,显示在Test.razor中。事实上,在TestRazor.cs中,它总是保持false,即使在检查值时它是正确的。

我哪里错了?

我通过将父组件(Test)作为级联参数传递给TableCell组件并调用父方法来解决这个问题,父方法调用" stathaschanged ()"当子组件中的复选框发生更改时:

Test.razor.cs:

namespace Accounting.Web.Components.Test
{
public class TestRow<TItem>
{
public TItem Item { get; set; } = default!;
public int Id { get; set; } = default!;
public bool Checked = false;
}
public partial class Test<TItem>
{
//....
public void Refresh()
{
StateHasChanged();
}    
}
}

TestCell.razor.cs:

namespace Accounting.Web.Components.Test
{
public partial class TestCell<TItem>
{
[CascadingParameter]
public Test<TItem> Owner { get; set; } = default!;
[Parameter]
public TestRow<TItem> Row { get; set; } = default!;
[Parameter]
public RenderFragment ChildContent { get; set; } = default!;
public void OnCheckChanged(object checkedValue)
{
Row.Checked = (bool)checkedValue;
Owner.Refresh();
}
}
}

相关内容

  • 没有找到相关文章

最新更新