上篇準備好了菜單定義檔與對應的 XSD,這一篇要寫的是真正把 XML 變成介面的那支類別:MenuLoad。它負責三件事——驗證 XML、依 XML 建出菜單與工具列、以及把使用者點擊導向正確的表單。
public class MenuLoad
{
private PluginCollection m_plugins = null;
public MenuBar _menbar = new MenuBar();
public ToolStrip _toolbar = new ToolStrip();
private OutlookBar bar = new OutlookBar();
private ImageList imglist = new ImageList();
private StringBuilder builder = new StringBuilder();
public MenuLoad()
{
bar = _menbar.outlookBar;
}
private TabControl tabCtrl;
public TabControl TabCtrl
{
set { tabCtrl = value; }
}
菜單、工具列、OutlookBar 三種呈現形式都在這裡集合,而 StringBuilder builder 是專門用來累積驗證錯誤訊息的緩衝區。
XML 驅動的框架最怕設定檔寫錯卻要到執行期才爆掉。因此載入之前,先跑一次 XSD 驗證:
private void ValidationEventHandler(object sender, ValidationEventArgs e)
{
builder.AppendLine("驗證 XML 文檔的時候發生錯誤:");
builder.AppendLine("嚴重級別:" + e.Severity);
builder.AppendLine("錯誤信息:" + e.Message);
builder.AppendLine("------+--------+-------+------+--------+-------+------+--------+-------+");
builder.AppendLine();
}
private bool ValidateXml(string XMLfile)
{
bool validXML = false;
string spath = Application.StartupPath + @"configurations\XMLS\Menu.xsd";
if (!System.IO.File.Exists(spath))
throw new System.IO.FileNotFoundException(
String.Format(Resources.StringFileNotFound, spath));
XmlReaderSettings settings = new XmlReaderSettings();
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add(null, spath);
settings.Schemas.Add(schemaSet);
settings.ValidationType = ValidationType.Schema;
settings.ValidationEventHandler +=
new ValidationEventHandler(ValidationEventHandler);
settings.ValidationFlags |=
XmlSchemaValidationFlags.ReportValidationWarnings;
XmlReader reader = XmlReader.Create(XMLfile, settings);
while (reader.Read()) { } // 只是讓它走完,觸發驗證
validXML = (builder.Length == 0);
reader.Close();
return validXML;
}
設計上有一個關鍵點:驗證不是丟例外,而是透過 ValidationEventHandler 把所有問題累積到 builder。讀完之後只要 builder 不是空的,就代表設定檔有問題,而且一次就能拿到全部錯誤清單,不必修一個、試一次。
public MainMenu LoadMenus(string XMLfile)
{
MainMenu mainmenu = new MainMenu();
try
{
using (new WaitCursor())
{
if (ValidateXml(XMLfile))
{
XmlDocument document = new XmlDocument();
document.Load(XMLfile);
XmlNode rootNode = document.DocumentElement;
mainmenu = GetMenus(rootNode);
}
else
{
throw new Exception(builder.ToString());
}
}
}
catch (System.IO.FileNotFoundException)
{
Utility.ShowErrorMsg(String.Format(Resources.StringFileNotFound, XMLfile));
}
return mainmenu;
}
WaitCursor 是一個 IDisposable 的小工具,進入時換上忙碌游標、離開時還原。用 using 包起來,即使中途丟例外也不會把游標留在忙碌狀態。
這裡刻意分成兩趟。第一趟只處理第一層,讓主菜單能立刻顯示出來,避免使用者盯著空白視窗等整棵樹建完:
private MainMenu GetMenus(XmlNode node)
{
MainMenu mainmenu = new MainMenu();
List<XmlNode> nodelist = new List<XmlNode>();
List<OfficeMenuItem> mnulist = new List<OfficeMenuItem>();
List<IconPanel> iplist = new List<IconPanel>();
// 先載入主菜單,避免迭代時菜單顯示得過分延遲
foreach (XmlNode child in node.ChildNodes)
{
if (child.NodeType == XmlNodeType.Element && child.Name == "MenuItem")
{
string menutext = child.Attributes["Name"].Value;
OfficeMenuItem item = new OfficeMenuItem(true, menutext);
mainmenu.MenuItems.Add(item);
IconPanel cp = new IconPanel();
bar.AddBand(menutext, cp);
nodelist.Add(child);
mnulist.Add(item);
iplist.Add(cp);
}
}
GetSubMenus(iplist.ToArray(), mnulist.ToArray(), nodelist.ToArray());
return mainmenu;
}
三個平行清單 nodelist/mnulist/iplist 以相同索引對應:第 i 個 XML 節點、第 i 個菜單項、第 i 個 OutlookBar 分頁。這種「平行陣列」的寫法不如自訂一個資料類別來得優雅,但在這種一次性建構的場景裡夠用。
private void GetSubMenus(IconPanel[] iplist, OfficeMenuItem[] main, XmlNode[] node)
{
EventHandler handler = new EventHandler(OnPluginClick);
EventHandler handler1 = new EventHandler(OnIconClick);
EventHandler handler2 = new EventHandler(OnButtonClick);
for (int i = 0; i <= main.GetUpperBound(0); i++)
{
for (int j = 0; j < node[i].ChildNodes.Count; j++)
{
XmlNode child = node[i].ChildNodes[j];
if (child.NodeType == XmlNodeType.Element && child.Name == "MenuItem")
{
string asmname = child.Attributes["AssemblyName"].Value;
string formtag = child.Attributes["FormTag"].Value;
string text = child.Attributes["Name"].Value;
string msc = child.Attributes["ShortCut"].Value;
string iconname = child.Attributes["Image"].Value;
string iconpath = "";
OfficeMenuItem item = new OfficeMenuItem(true, text, handler);
if (iconname != string.Empty)
{
iconpath = Themes.GetCurrentThemePath() + iconname;
item.IconPath = iconpath;
}
MenuClass mc = new MenuClass();
mc.Assemblyname = asmname;
mc.FormTag = formtag;
item.Tag = mc; // 把目標資訊掛在 Tag 上
if (msc != string.Empty)
item.Shortcut = MenuShortCut.GetShortCut(msc);
main[i].MenuItems.Add(item);
if (iconpath != string.Empty && System.IO.File.Exists(iconpath))
{
PanelIcon picon = iplist[i].AddIcon(
item.Text, Image.FromFile(iconpath), handler1);
picon.Tag = mc;
ToolStripButton button = new ToolStripButton(
item.Text, Image.FromFile(iconpath), handler2);
button.DisplayStyle = ToolStripItemDisplayStyle.Image;
button.ToolTipText = item.Text;
button.Tag = mc;
button.Visible = true;
_toolbar.Items.Add(button);
}
if (child.ChildNodes.Count > 0)
GetChildMenu(iplist[i], item, child); // 遞迴處理下一層
}
}
_toolbar.Items.Add(new ToolStripSeparator());
}
}
這裡有兩個值得留意的技巧。一是 MenuClass 被掛進每個控制項的 Tag 屬性,於是無論使用者從菜單、OutlookBar 圖示還是工具列按鈕觸發,事件處理器都能用同一種方式取回「該開哪支程式集、哪個表單」;三個 handler 因此可以共用同一段後續邏輯。二是 GetChildMenu 的遞迴呼叫,讓 XML 可以嵌套到任意層次,而程式碼完全不必為層數寫死。
private void OpenForm(MenuClass mc)
{
string asmname = mc.Assemblyname;
string formtag = mc.FormTag;
if (formtag == "")
throw new Exception(Resources.StringNoFormFlag);
if (formtag.ToUpper() == "TRUE")
{
if (asmname == string.Empty)
throw new NullReferenceException(Resources.StringAssemblyNull);
object obj = null;
Type tp = Type.GetType(asmname);
if (tp != null)
obj = Activator.CreateInstance(tp);
else
throw new Exception("加載程序的時候出錯,請檢查程序(dll,exe)是否存在或者類型是否正確。");
if ((obj == null) | !(obj is Form))
throw new Exception(Resources.StringNotForm);
Form frm = (obj as Form);
// 若主視窗是 MDI 容器,就掛成子表單
if (Application.OpenForms[0].IsMdiContainer)
frm.MdiParent = Application.OpenForms[0];
frm.Show();
}
}
Type.GetType("命名空間.類別, 組件") 加上 Activator.CreateInstance,就是整個模組化能力的來源:主程式不需要在編譯期知道任何一個功能模組的存在,只要在 XML 裡寫對字串,就能在執行期把對應表單拉起來。新增模組因此不必重新編譯主程式,也不必改動主程式的任何一行程式碼。
private void OnPluginClick(object sender, EventArgs args)
{
OfficeMenuItem item = (OfficeMenuItem)sender;
MenuClass mc = (MenuClass)item.Tag;
if ((item.Text == "退出") | (item.Text == "EXIT"))
{
OnExitClick(sender, args);
return;
}
OpenForm(mc);
}
「退出」是內建保留字,直接導向關機流程,其餘全部交給 OpenForm。這個分流點也是很好的擴充位置——例如要加上權限檢查,只要在使用者身分不符時攔下 OpenForm 呼叫即可。
整支 MenuLoad 的核心其實只有兩個函式:負責建構的 LoadMenus 與負責分流的 OnPluginClick,兩者靠 delegate 串起來。透過它,可以動態增加任意層次的模組,介面的菜單、圖示、工具列全部由設定檔決定。
和微軟 CAB 的 RegisterSite 那套註冊式做法相比,XML 配置的方式視覺上更直觀:一條設定對應一個功能入口,改動成本極低。當然它也有代價——反射帶來的效能與型別安全風險、設定檔錯誤只能靠執行期發現(因此驗證環節才如此重要),以及 Tag 這種弱型別傳遞參數的做法,規模一大就容易出錯。若要在正式產品中沿用這套思路,建議把 MenuClass 改成強型別的模組描述物件,並在 OpenForm 之前補上一層介面契約檢查(例如要求模組實作 IModule),讓錯誤在更早的階段被攔下。