LoginSignup
4
0

More than 1 year has passed since last update.

Blazorでダイアログを出したい

Last updated at Posted at 2022-03-18

Step1_ダイアログのテンプレート

TemplateDialog.razor
@if (isShow)
{
<div class="dialog-outer" @onclick="@(() => this.Close())">
    <div class="dialog-content" @onclick:stopPropagation="true">
        @ChildContent
    </div>
</div>
}


@code {
    [Parameter]
    public RenderFragment ChildContent { get; set; } = null!;

    private bool isShow;

    public void Show()
    {
        this.isShow = true;
        this.StateHasChanged();
    }

    public void Close()
    {
        this.isShow = false;
        this.StateHasChanged();
    }
}
TemplateDialog.razor.css
.dialog-outer {
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    top: 0px;
    left: 0px;
    width: 100vw;
    height: 100vh;
    background-color: rgba(75, 85, 99, 0.8);
}

.dialog-content{
    max-height: 90vh;
    max-width: 90vh;
    overflow: auto;
    background-color: white;
}

Step2_ダイアログの基底クラス

AbstractDialog.cs
    public abstract class AbstractDialog : ComponentBase
    {
        /// <summary>
        /// Dialog参照
        /// </summary>
        protected TemplateDialog TemplateDialog { get; set; } = new TemplateDialog();

        /// <summary>
        /// ダイアログを開く
        /// </summary>
        public virtual void Show()
        {
            TemplateDialog.Show();
        }

        /// <summary>
        /// ダイアログを閉じる
        /// </summary>
        public virtual void Close()
        {
            TemplateDialog.Close();
        }
    }

Step3_好きなダイアログ作る

TemplateDialog.razor
@inherits AbstractDialog

<TemplateDialog @ref="TemplateDialog">
    <h2>ダイアログサンプル</h2>
    <hr />
    <hr />
    <p>本日は晴天なり本日は晴天なり</p>
    <p>あいうえおカキクケコ</p>


    @*Close()を呼び出して閉じる*@
    <Button @onclick="()=> this.Close()">閉じる</Button>
</TemplateDialog>

Step4_ダイアログを呼び出したい画面に貼り付ける

Index.razor
@page "/"

// step2 - ダイアログの参照紐付けて
<TemplateDialog @ref="_dialog" />

// step3 - 好きなタイミングで.Show()を呼ぶ
<button @onclick="()=> _dialog.Show()">開く</button>
@code{
    // step1 - ダイアログインスタンス作って
    private TemplateDialog _dialog = new TemplateDialog();
}

結果

image.png

閉じるボタンか背景のグレーをタッチするとダイアログが消えます。
image.png

4
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0