我們這一篇想來點共用的元件(Component),用 Bootstrap 的對話視窗(Modal) 來顯示指定的訊息。
緣起
剛好小喵想要一個共用的元件,使用Bootstrap的Modal來顯示指定的訊息,所以測試了一下相關的撰寫方式,並筆記下來,以供後來有需要時參考。
Data
我們建立一個類別,用來存放該視窗需要的一些屬性,相關程式碼如下:
    public class MsgInfo
    {
        /// <summary>
        /// 訊息標題
        /// </summary>
        public string Title { get; set; } = "";
        /// <summary>
        /// 訊息內容
        /// </summary>
        public string Msg { get; set; } = "";
        /// <summary>
        /// 是否顯示訊息
        /// </summary>
        public bool showMsg { get; set; } = false;
    }
元件(Component):ShowMsg.razor
接著撰寫元件本身的內容,相關程式碼如下:
@if (showMsg)
{
    <!-- Modal -->
    <div class="modal fade show" id="exampleModal" tabindex="-1" style="display:block" role="dialog" aria-modal="true" aria-labelledby="exampleModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="exampleModalLabel">@Title</h5>
                    <button type="button" class="close" aria-label="Close" @onclick="CloseMsg">
                        <span aria-hidden="true">×</span>
                    </button>
                </div>
                <div class="modal-body">
                    @((MarkupString)Msg)
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-primary" @onclick="CloseMsg">關閉</button>
                    
                </div>
            </div>
        </div>
    </div>
    <!--End Modal-->
}
@code {
    [Parameter]
    public bool showMsg { get; set; } = false;
    [Parameter]
    public string Title { get; set; } = "";
    [Parameter]
    public string Msg { get; set; } = "";
    private void CloseMsg()
    {
        showMsg = false;
    }
}
測試使用
我們在 Index.razor 裡面,撰寫測試的相關程式碼如下:
@page "/"
@using BlazorComponentParameter.Data;
<h1>Hello, world!</h1>
Welcome to your new app.
<ShowMsg Title="@oMsg.Title" Msg="@oMsg.Msg" showMsg="@oMsg.showMsg"></ShowMsg>
    
<button @onclick="testMsg">顯示訊息</button>
<SurveyPrompt Title="How is Blazor working for you?" />
@code{
    private MsgInfo oMsg = new MsgInfo();
    private void testMsg()
    {
        string NowTime = DateTime.Now.ToString("HH:mm:ss");
        oMsg.Title = "測試標題-" + NowTime;
        oMsg.Msg = "測試內容-<br>" + NowTime;
        oMsg.showMsg = true;
    }
}
測試運行相關畫面如下:


末記
整理一下本篇用到的一些技巧,包括:
- 元件(Component)使用參數(Parameter)
 - 套用元件,使用參數結合變數
 - Code中設定變數,連動參數
 - Bootstrap Modal直接顯示
 - 透過Code變數控制Modal顯示與隱藏
 
筆記提供未來自己參考
^_^
以下是簽名:
- 歡迎轉貼本站的文章,不過請在貼文主旨上加上【轉貼】,並在文章中附上本篇的超連結與站名【topcat姍舞之間的極度凝聚】,感恩大家的配合。
 - 小喵大部分的文章會以小喵熟悉的語言VB.NET撰寫,如果您需要C#的Code,也許您可以試著用線上的工具進行轉換,這裡提供幾個參考
 
| Microsoft MVP Visual Studio and Development Technologies (2005~2019/6)  | topcat Blog:http://www.dotblogs.com.tw/topcat  |