c# - 如何在 Blazor 中以两种方式绑定级联值?
问题描述
我正在使用 Blazor 中的自定义模板,并试图找到一种双向绑定 aCascadingValue
或实现类似功能的方法。现在我有以下模板。
@if (PopupVisible)
{
<DxPopup>
<HeaderTemplate>
<h4 class="modal-title">@HeaderText</h4>
<button type="button" class="close" @onclick="@UpdatePopupVisible">×</button>
</HeaderTemplate>
<ChildContent>
<div class="modal-body">
<div class="container-fluid">
@bodyContent
</div>
</div>
<div class="modal-footer">
@footerContent
<button class="btn btn-secondary" @onclick="UpdatePopupVisible">Cancel</button>
</div>
</ChildContent>
</DxPopup>
}
@code {
[CascadingParameter] public bool PopupVisible { get; set; }
[CascadingParameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
[Parameter] public RenderFragment HeaderText { get; set; }
[Parameter] public RenderFragment footerContent { get; set; }
[Parameter] public RenderFragment bodyContent { get; set; }
private async Task UpdatePopupVisible()
{
PopupVisible = false;
await PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
然后我有一个实现这个模板(子)的组件,然后我有一个用按钮按下(父)调用的组件。我想知道的是是否有一种方法可以PopupVisible
从父级绑定参数,而不必将其绑定到子级并让子级将其传递给模板。我还没有找到双向绑定级联参数的方法,但如果可能的话,我认为这将是最好的方法。除此之外,我不确定是否还有其他方法,或者我将不得不接受我目前传递价值的想法。
解决方案
You can't do two-way binding with cascading parameters. Cascading means flowing downstream, from parent to child, and not the other way around.
I'm not sure I understand your question...however, if you wish to pass a value from a parent component and back; you can do the following: Note: This is a two-way Component data binding
Child Component
@code
{
private bool visible;
[Parameter]
public bool PopupVisible
{
get { return visible }
set
{
if (visible != value)
{
visible = value;
}
}
}
[Parameter] public EventCallback<bool> PopupVisibleChanged { get; set; }
// Invoke the EventCallback to update the parent component' private field visible with the new value.
private Task UpdatePopupVisible()
{
PopupVisible = false;
return PopupVisibleChanged.InvokeAsync(PopupVisible);
}
}
Usage
@page "/"
<DxPopup @bind-PopupVisible="visible" />
@code {
private bool visible;
}
Note: If you need some explanation, and believe that I did not answer your question, don't hesitate to tell me, but please take the time to phrase your questions... I could not completely understand questions.
推荐阅读
- git - Atlassian bitbucket 和竹子的区别
- c# - 从 C# 类获取 JSON PropertyName,例如 json 属性的“nameof(class.prop)”?
- flask-sqlalchemy - Alembic sqlalchemy.exc.NoReferencedColumnError:(使用 Flask-sqlalchemy 和 Flask-Migrate)
- android - 我在 Android 中使用新的 Places SDK。AutocompleteSupportFragment 要求我将活动添加到清单中
- node.js - 如何避免“TypeError:popper.js.map 不是有效的 URL”消息
- excel - 如果单元格等于一组值,则删除行
- c# - 为什么我的下拉列表选择相同的值?
- python - 在上下文管理器中处理文件系统撤消操作的简洁有效的方法
- angular - 尝试在不属于组件的模板文件中使用枚举
- python - Python/Pandas:跨数据帧的复杂 Excel SUMIFS