C#/Vsto中CustomTaskPanes和Ribbon的使用方法
在工作中有一個需求,需要添加工作區選項卡,Excel中CustomTaskPanes面板很適合這樣的場景,而非集中處理在Excel的Ribbon面板中,畢竟在大型項目中表現層已經過於複雜了。首先寫一個顯示Panes的方法。
var sr = new OtherShouldReceiveUserControl(Wb, Wb.Application); var dpi = sr.dpiValue; sr.Name = "OtherShouldReceiveUserControl"; var customTaskPane = Globals.ThisAddIn.CustomTaskPanes.Add(sr, "快速導航"); customTaskPane.DockPosition = MsoCTPDockPosition.msoCTPDockPositionFloating; customTaskPane.DockPositionRestrict = MsoCTPDockPositionRestrict .msoCTPDockPositionRestrictNoChange; customTaskPane.Visible = true;
而這個方法我們會在worksheet active中觸發。
app = Globals.ThisAddIn.Application;
app.SheetActivate += App_SheetActivate;
private void App_SheetActivate(object Sh)
{
CommonUtils.CallShowNavicatButton(CurWorkbook, curWorksheet.Name);
}
在SheetActive中調用方法,不過有一個問題,每次Active處罰之後都會Add OtherShouldReceiveUserControl 用戶控制項,它會出現用戶控制項重複添加的情況,所以你需要做一定的冗餘處理。如何處理呢?
Worksheet worksheet = Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet; var EnableNavicat = GetEnableNavicat(); if (EnableNavicat == "false") { return; } if (Wb.Application.Visible) { #region 刪除導航,激活其他excel必須用目前方法 int i = -1; int deleteIndex = -1; foreach (var panel in Globals.ThisAddIn.CustomTaskPanes) { i++; try { if (panel != null && (panel.Title == "快速導航") { panel.Visible = false; deleteIndex = i; break; } } catch { } } if (deleteIndex >= 0) { //移除導航 try { Globals.ThisAddIn.CustomTaskPanes.RemoveAt(deleteIndex); } catch { } }
首先遍歷 Globals.ThisAddIn.CustomTaskPanes 中的所有panel,如果Title是我們剛才添加的,或許你可以使用Tag來判斷,這由你而定。隨後通過 RemoveAt 方法來進行Delete操作。值得注意還有一個參數需要說說, MsoCTPDockPosition 改變Panel的 DockPosition 排列方式。一般使用Float即可。
// // 摘要: // Specifies the docking behavior of the custom task pane. public enum MsoCTPDockPosition { // // 摘要: // Dock the task pane on the left side of the document window. msoCTPDockPositionLeft = 0, // // 摘要: // Dock the task pane at the top of the document window. msoCTPDockPositionTop = 1, // // 摘要: // Dock the task pane on the right side of the document window. msoCTPDockPositionRight = 2, // // 摘要: // Dock the task pane at the bottom of the document window. msoCTPDockPositionBottom = 3, // // 摘要: // Don't dock the task pane. msoCTPDockPositionFloating = 4 }
在此之前,我要創建一個Ribbon,百思不得其解的是Vsto是否只對應一個Ribbon面板,或者說是可以綁定多個,我多次試驗後,發現是vsto項目確實對應一個Ribbon,當你創建了Vsto項目你會發現你的項目中還沒有Ribbon,你需要手動創建。如圖下。
你以為這樣你的項目中就生效了嗎,你還需要將 Controlid 改為Custom,如果你想要第二個TabRibbon,你不需要在創建一個Ribbon,如果你創建了2個,那將都不顯示,所有隻能再創建一個Tab綁定一個 Controlid 。此時此刻,如圖所示,已經達到了我們的效果。
感謝您閱讀本篇文章,祝您工作順利。