1. 程式人生 > 其它 >Blazor使用級聯值實現Dialog關閉功能

Blazor使用級聯值實現Dialog關閉功能

思路

1.在模板頁面增加CascadingValue傳入Dialog的例項
2.在BaseComponent中加入[CascadingParameter]特性宣告級聯Dialog例項引數
3.在模組頁面按鈕方法中呼叫Dialog例項引數的Close方法

模板頁面

<div class="app">
    <CascadingValue Value="dialog">
        <DynamicComponent Type="componentType" />
    </CascadingValue>
</div>
<Dialog @ref="dialog" />
@code {
    private Dialog dialog;
    private Type componentType;
}

BaseComponent

public class BaseComponent : ComponentBase, IDisposable {
    [CascadingParameter]
    protected Dialog Dialog { get; set; }
}

模組頁面

@inherits BaseComponent
<div>
    <button @onclick="OnOpen">開啟</button>
</div>
@code {
    private void OnOpen() {
        UI.Show(new DialogOption{
            Title = "測試",
            Content = builder => {
                builder.Element("button", b => {
                    b.Text("關閉").OnClick(EventCallback.Factory.Create(this, e => Dialog.Close()));
                })
            }
        });
    }
}