[Blazor][筆記][ComponentBase]透過繼承自訂ComponentBase,撰寫各Component共用程式碼

以前在 WebForm 針對頁面會有 PageBase , MVC 的 Controller 會有 ControllerBase,那麼在撰寫 Blazor 的 Component 是否也是會有 ComponentBase ,有的,來喔~

緣起

以前在 WebForm 針對頁面會有 PageBase , MVC 的 Controller 會有 ControllerBase,那麼在撰寫 Blazor 的 Component 是否也是會有 ComponentBase ,有的,來喔~

繼續上一篇,我們把顯示訊息的部分,透過 ComponentBase ,把使用顯示訊息再修改得更簡易使用一點。

修改 MsgInfo

承繼上一篇【[筆記][Blazor]使用對話視窗Component無法動作與解決方式】,我們需要在顯示訊息的 Component 中加上一個NowTime的參數,讓他每次的呼叫,都有狀態的改變。如果是剛進入看這一篇的朋友,建議看一下那一篇。

我們本來是在每次要顯示訊息時,透過屬性把NowTime的內容放入。我們稍微修改一下MsgInfo的內容,讓我們去設定showMsg的屬性時,可以直接取當下的時間,並且讓MsgInfo的NowTime變成ReadOnly的屬性。

原本的 MsgInfo.cs

public class MsgInfo
{
	public string Title { get; set; } = "";
	public string Msg { get; set; } = "";
	public bool showMsg { get; set; } = false;
	public string NowTime { get; set; } = "";
}

修改後的 MsgInfo

public class MsgInfo
{
	private bool _showMsg = false;
	private string _NowTime;

	public string Msg { get; set; } = "";

	public string Title { get; set; } = "";

	public bool showMsg 
	{
		get { return _showMsg; } 
		set 
		{
			_showMsg = value;
			_NowTime = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
		} 
	} 

	public string NowTime
	{
		get
		{
			return _NowTime;
		}
	}
}

這樣每次在設定屬性 showMsg 的時候,就可以給新的 NowTime

建立 MyComponentBase.cs

我們可以再新增一個類別在 DAOs 資料夾,命名為【MyComponentBase】,相關內容如下:

using BlazorCRUDLifeCycle.Data;
using Microsoft.AspNetCore.Components;

namespace BlazorCRUDLifeCycle.DAOs
{
    public class MyComponentBase : ComponentBase
    {
        public MsgInfo oMsg = new MsgInfo();

        public void ShowMsg(string Msg, string Title = "訊息:")
        {
            oMsg.Title = Title;
            oMsg.Msg = Msg;
            oMsg.showMsg = true;
        }
    }
}

醬子,要顯示訊息時,只需要呼叫 ShowMsg 這個 Function 就可以。

改 Component 名稱

由於Function名稱,Component 名稱都是 ShowMsg,因此想說把Component的名稱稍微改一下。在修改的過程中,Visual Studion很貼心的在修改 Component 名稱的時候,會主動地掃有使用的相關程式碼,並且協助您把名稱改掉。小喵就把Component名稱改為【ShowMsgCpn】

套用 MyComponentBase

在要套用的元件中,只須加上【inherits】的宣告即可套用

@inherits MyComponentBase;

在畫面中,當然要安排一下套用 ShowMsgCpn

<ShowMsgCpn Title="@oMsg.Title" Msg="@oMsg.Msg" showMsg="@oMsg.showMsg" NowTime="@oMsg.NowTime"></ShowMsgCpn>

在程式碼中,要顯示訊息,就直接呼叫ShowMsg的Function即可

//oMsg.Title = "訊息:";
//oMsg.Msg = rc;
//oMsg.showMsg = true;
//oMsg.NowTime = NowTime;
ShowMsg(rc);
StateHasChanged();

 

 


以下是簽名:


Microsoft MVP
Visual Studio and Development Technologies
(2005~2019/6) 
topcat
Blog:http://www.dotblogs.com.tw/topcat