您需要将级联状态对象与事件一起使用。使用
@ref
这不是该走的路。这是一种常见的通知模式,用于DateTime。如果你在SO中搜索“SequenceNotification Pattern”,你会发现关于这个主题的几个答案。
您可以级联状态对象
表格
级别上下文或将其注册为
SPA会议
水平上下文。
这是一个快速而肮脏的演示。
public class CardState
{
public bool AllOpen { get; private set; }
public event EventHandler<bool>? StateChanged;
public void CloseAllCards()
{
AllOpen = false;
this.StateChanged?.Invoke(this, this.AllOpen);
}
public void OpenAllCards()
{
AllOpen = true;
this.StateChanged?.Invoke(this, this.AllOpen);
}
}
一张非常简单的卡片
@implements IDisposable
@if (_isOpen)
{
<div class="card my-2">
<div class="m-2 text-end">
<button class="btn btn-dark" @onclick="this.Close">Close</button>
</div>
<div class="card-body">Basic card</div>
</div>
}
@code {
[CascadingParameter] private CardState? CardState { get; set; }
[Parameter] public bool IsInitiallyOpen { get; set; } = true;
private bool _isOpen = true;
protected override void OnInitialized()
{
_isOpen = this.IsInitiallyOpen;
if (this.CardState is not null)
this.CardState.StateChanged += this.OnStateChanged;
}
protected void Close()
{
_isOpen = false;
}
private void OnStateChanged(object? sender, bool state)
{
_isOpen = state;
// must call here as this is not a UI event
this.StateHasChanged();
}
public void Dispose()
{
if (this.CardState is not null)
this.CardState.StateChanged -= this.OnStateChanged;
}
}
演示页面
@page "/"
<PageTitle>Home</PageTitle>
<h1>Hello, world!</h1>
<div class="m-2 p-2 text-end">
<button class="btn btn-primary" @onclick="ChangeState">Change</button>
</div>
<CascadingValue Value="_cardState">
<Card />
<Card />
<Card />
<Card />
</CascadingValue>
@code {
private readonly CardState _cardState = new();
private void ChangeState()
{
if (_cardState.AllOpen)
_cardState.CloseAllCards();
else
_cardState.OpenAllCards();
}
}