演练:使用上下文选项卡创建自定义 Web 部件

上次修改时间: 2011年2月4日

适用范围: SharePoint Foundation 2010

本文内容
创建 SharePoint 项目
实现 Web 部件
创建页面组件
部署自定义项

本主题演示如何在 Microsoft SharePoint Foundation 中创建可在服务器功能区上打开上下文选项卡的自定义 Web 部件。

先决条件

Microsoft SharePoint Foundation 2010

Microsoft Visual Studio 2010 中的 SharePoint 开发工具

创建 SharePoint 项目

若要创建 Web 部件和功能区自定义项,需要从创建一个空 SharePoint 项目开始。

创建 SharePoint 项目

  1. 启动 Visual Studio 2010。

  2. 在"文件"菜单上,指向"新建",然后单击"项目"。

  3. 在"项目类型"中,在"C#"下选择"空 SharePoint 项目"。

  4. 键入 ContextualTabWebPart 作为项目名称。然后单击"确定"。

  5. 在"SharePoint 自定义向导"中,选择"部署为场解决方案",然后单击"完成"。

实现 Web 部件

现在,您可以实现 Web 部件

实现 Web 部件

  1. 在"解决方案资源管理器"中,右键单击"引用",然后选择"添加引用"。

  2. 在"添加应用"对话框中,选择".NET"选项卡,然后选择"Microsoft.Web.CommandUI.dll"。单击"确定"。

  3. 在"解决方案资源管理器"中,右键单击"ContextualTabWebPart"项目,指向"添加",然后选择"新建项目"。

  4. 在"添加新项目"对话框中,选择"Web 部件"。键入 ContextualTabWebPart 作为名称。

  5. 添加了 Web 部件并且 ContextualTabWebPart.cs 文件显示后,再添加以下语句。

    using System.Xml;
    using Microsoft.Web.CommandUI;
    
  6. 接下来,需要实现下面代码中所示的 IWebPartPageComponentProvider 接口。您将在稍后完成此工作。

    public class ContextualTabWebPart : WebPart, IWebPartPageComponentProvider
    

    接下来,您需要为功能区 XML 创建两个全局字符串变量。这两个变量定义上下文选项卡和组模板。有关功能区 XML 的详细信息,请参阅服务器功能区 XML

  7. 在 contextualTab 字符串中,注意 ContextualGroup 元素。该元素将以下 Tab 元素定义为上下文选项卡。Color 属性定义选项卡呈现时的颜色。Id 和 ContextualGroupId 是组的唯一标识符。Sequence 属性定义上下文选项卡的呈现位置。下面的代码实现两个全局字符串变量。

    private string contextualTab = @"
       <ContextualGroup Color=""Magenta"" 
         Command=""CustomContextualTab.EnableContextualGroup"" 
         Id=""Ribbon.CustomContextualTabGroup"" 
         Title=""Custom Contextual Tab Group"" 
         Sequence=""502"" 
         ContextualGroupId=""CustomContextualTabGroup"">
              <Tab 
                  Id=""Ribbon.CustomTabExample"" 
                  Title=""My Custom Tab"" 
                  Description=""This holds my custom commands!"" 
                  Command=""CustomContextualTab.EnableCustomTab"" 
                  Sequence=""501"">
                <Scaling
                  Id=""Ribbon.CustomTabExample.Scaling"">
                  <MaxSize
                    Id=""Ribbon.CustomTabExample.MaxSize"" 
                    GroupId=""Ribbon.CustomTabExample.CustomGroupExample"" 
                    Size=""OneLargeTwoMedium""/>
                  <Scale 
                    Id=""Ribbon.CustomTabExample.Scaling.CustomTabScaling""
                    GroupId=""Ribbon.CustomTabExample.CustomGroupExample"" 
                    Size=""OneLargeTwoMedium"" />
                </Scaling>
                <Groups Id=""Ribbon.CustomTabExample.Groups"">
                  <Group 
                    Id=""Ribbon.CustomTabExample.CustomGroupExample"" 
                    Description=""This is a custom group!"" 
                    Title=""Custom Group"" 
                    Command=""CustomContextualTab.EnableCustomGroup"" 
                    Sequence=""52"" 
                    Template=""Ribbon.Templates.CustomTemplateExample"">
                    <Controls 
                      Id=""Ribbon.CustomTabExample.CustomGroupExample.Controls"">
                      <Button 
                        Id=""Ribbon.CustomTabExample.CustomGroupExample.HelloWorld"" 
                        Command=""CustomContextualTab.HelloWorldCommand"" 
                        Sequence=""15"" 
                        Description=""Says hello to the World!"" 
                        LabelText=""Hello, World!"" 
                        TemplateAlias=""cust1""/>
                      <Button 
                        Id=""Ribbon.CustomTabExample.CustomGroupExample.GoodbyeWorld"" 
                        Command=""CustomContextualTab.GoodbyeWorldCommand"" 
                        Sequence=""17"" 
                        Description=""Says good-bye to the World!"" 
                        LabelText=""Good-bye, World!"" 
                        TemplateAlias=""cust2""/>
                    </Controls>
                  </Group>
                </Groups>
              </Tab>
       </ContextualGroup>";
     
            private string contextualTabTemplate = @"
              <GroupTemplate Id=""Ribbon.Templates.CustomTemplateExample"">
                <Layout 
                  Title=""OneLargeTwoMedium"" LayoutTitle=""OneLargeTwoMedium"">
                  <Section Alignment=""Top"" Type=""OneRow"">
                    <Row>
                      <ControlRef DisplayMode=""Large"" TemplateAlias=""cust1"" />
                    </Row>
                  </Section>
                  <Section Alignment=""Top"" Type=""TwoRow"">
                    <Row>
                      <ControlRef DisplayMode=""Medium"" TemplateAlias=""cust2"" />
                    </Row>
                    <Row>
                      <ControlRef DisplayMode=""Medium"" TemplateAlias=""cust3"" />
                    </Row>
                  </Section>
                </Layout>
              </GroupTemplate>";
    
  8. 创建一个名为 DelayScript 的新字符串属性。DelayScript 包含 ECMAScript(JavaScript、JScript),其添加并注册您的自定义页面组件。您将在本主题后面创建自定义页面组件。_addCustomPageComponent 方法创建自定义页面组件并将其添加到页面管理器。每个 Web 部件都有一个页面组件,您将在创建自定义页面组件对象时使用 Web 部件的页面组件 ID。这对于将 Web 部件与页面组件相关联以启用到您的自定义功能区选项卡的上下文切换是必需的。_registerCustomPageComponent 方法在加载页面时注册您的 JavaScript 文件。

    以下代码实现 DelayScript。

            public string DelayScript 
            {
                get
                {
                    string webPartPageComponentId = SPRibbon.GetWebPartPageComponentId(this);
                    return @"
    <script type=""text/javascript"">
    //<![CDATA[
     
                function _addCustomPageComponent()
                {
                    var _customPageComponent = new ContextualTabWebPart.CustomPageComponent('" + webPartPageComponentId + @"');
                    SP.Ribbon.PageManager.get_instance().addPageComponent(_customPageComponent);
                }
     
                function _registerCustomPageComponent()
                {
                    SP.SOD.registerSod(""CustomContextualTabPageComponent.js"", ""\/_layouts\/CustomContextualTabPageComponent.js"");
                    SP.SOD.executeFunc(""CustomContextualTabPageComponent.js"", ""ContextualWebPart.CustomPageComponent"", _addCustomPageComponent);
                }
                SP.SOD.executeOrDelayUntilScriptLoaded(_registerCustomPageComponent, ""sp.ribbon.js"");
    //]]>
    </script>";
                }
            }
    
  9. 创建一个名为 AddContextualTab 的新函数。在 AddContextualTab 方法内,您需要插入代码以将上下文选项卡和自定义模板注册到功能区。RegisterDataExtension(XmlNode, String) 方法可用于注册功能区扩展名。RegisterDataExtension(XmlNode, String) 提示功能区在何处加载传入到其中的 XML。您将使用 CMDUI.xml 中 ContextualTabs 和 Templates 元素的 ID。

    以下代码实现 AddContextualTab 方法。

            private void AddContextualTab()
            {
     
                // Get the current instance of the ribbon on the page.
                Microsoft.Web.CommandUI.Ribbon ribbon = SPRibbon.GetCurrent(this.Page);
     
                // Prepare an XmlDocument object used to load the ribbon extensions.
                XmlDocument ribbonExtensions = new XmlDocument();
     
                // Load the contextual tab XML and register the ribbon extension.
                ribbonExtensions.LoadXml(this.contextualTab);
                ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.ContextualTabs._children");
     
                // Load the custom templates and register the ribbon extension.
                ribbonExtensions.LoadXml(this.contextualTabTemplate);
                ribbon.RegisterDataExtension(ribbonExtensions.FirstChild, "Ribbon.Templates._children");
            }
    
  10. 现在,您必须实现 IWebPartPageComponentProvider 接口的 WebPartContextualInfo 属性。若要实现该接口,请右键单击"IWebPartPageComponentProvider",选择"实现接口",然后选择"显式实现接口"。

    该接口让功能区知道何时选中 Web 部件以及要显示哪些上下文组和选项卡。添加上下文组时,会向该接口发送上下文组的 ID、VisibilityContext 以及 Command。该 ID 映射到功能区 XML 中的 ContextualGroup 元素的 Id 属性。VisibilityContext 用于对控件分组,以显示或隐藏它们。Command 参数映射到功能区 XML 中的 ContextualGroup 元素的 Command。您还需要添加在功能区 XML 中定义的选项卡。必须只传入该选项卡的 Id 和 VisibilityContext 参数。插入以下用于 WebPartContextualInfo 的代码。

            public WebPartContextualInfo WebPartContextualInfo
            {
                get 
                {
                    WebPartContextualInfo info = new WebPartContextualInfo();
                    WebPartRibbonContextualGroup contextualGroup = new WebPartRibbonContextualGroup();
                    WebPartRibbonTab ribbonTab = new WebPartRibbonTab();
     
                    // Create the contextual group object and initialize its values.
                    contextualGroup.Id = "Ribbon.CustomContextualTabGroup";
                    contextualGroup.Command = "CustomContextualTab.EnableContextualGroup";
                    contextualGroup.VisibilityContext = "CustomContextualTab.CustomVisibilityContext";
     
                    // Create the tab object and initialize its values.
                    ribbonTab.Id = "Ribbon.CustomTabExample";
                    ribbonTab.VisibilityContext = "CustomContextualTab.CustomVisibilityContext";
     
                    // Add the contextual group and tab to the WebPartContextualInfo.
                    info.ContextualGroups.Add(contextualGroup);
                    info.Tabs.Add(ribbonTab);
                    info.PageComponentId = SPRibbon.GetWebPartPageComponentId(this);
     
                    return info;
                }
            }
    
  11. 接下来,您需要实现 OnPreRender 方法。这允许您在页面上呈现功能区之前,将元素添加到功能区。在 OnPreRender 内,您将调用 AddContextualTab 方法并将 DelayScript 注册到 ClientScriptManager 中。

    以下代码实现 OnPreRender 方法。

            protected override void OnPreRender(EventArgs e)
            {
                base.OnPreRender(e);
     
                this.AddContextualTab();
     
                ClientScriptManager clientScript = this.Page.ClientScript;
                clientScript.RegisterClientScriptBlock(this.GetType(), "ContextualTabWebPart", this.DelayScript);
     
            }
    

    Web 部件已完成。下一步,创建页面组件。

创建页面组件

页面组件是用于与服务器功能区交互的 JavaScript 对象。有关页面组件的深度演练,请参阅开发服务器功能区的网页组件。为使页面组件正常运行,您必须使用模块将其部署到 %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\\TEMPLATES\LAYOUTS 目录。这样会启用功能区上的命令,并能够响应您在功能区 XML 中定义的命令。

添加和定义页面组件

  1. 在"解决方案资源管理器"中,右键单击"ContextualTabWebPart"项目,指向"添加",然后选择"新建项目"。

  2. 在"添加新项目"对话框中,选择"模块"模板并键入 CustomContextualTabPageComponent 作为名称。单击"添加"。

  3. 您不需要添加的默认文件。在"解决方案资源管理器"中删除"Elements.xml"和"Sample.txt"。

  4. 现在,必须添加 JavaScript 文件。右键单击"CustomContextualTabPageComponent",指向"添加",然后选择"新建项目"。

  5. 在"已安装的模板"列表中,在"Visual C#"下选择"Web"。选择"Jscript 文件"类型,并键入 CustomContextualTabPageComponent 作为名称。

  6. 您必须设置部署位置以确保该文件进入 _layouts 目录。若要执行此操作,请在"解决方案资源管理器"中选择"CustomContextualTabPageComponent.js"。在"属性"窗口中,将"部署类型"设置为"根文件"。打开"部署位置"属性并在"路径"属性中键入 TEMPLATE\LAYOUTS。

    将以下代码添加到 CustomContextualTabPageComponent.js 文件以实现您的自定义页面组件。

    Type.registerNamespace('ContextualTabWebPart');
     
    var _webPartPageComponentId;
    ContextualTabWebPart.CustomPageComponent = function ContextualTabWebPart_CustomPageComponent(webPartPcId) {
        this._webPartPageComponentId = webPartPcId;
        ContextualTabWebPart.CustomPageComponent.initializeBase(this);
    }
    ContextualTabWebPart.CustomPageComponent.prototype = {
     
        init: function ContextualTabWebPart_CustomPageComponent$init() {  },
     
        getFocusedCommands: function ContextualTabWebPart_CustomPageComponent$getFocusedCommands() {
            return ['CustomContextualTab.EnableCustomTab', 'CustomContextualTab.EnableCustomGroup', 'CustomContextualTab.HelloWorldCommand', 'CustomContextualTab.GoodbyeWorldCommand'];
        },
     
        getGlobalCommands: function ContextualTabWebPart_CustomPageComponent$getGlobalCommands() {
            return [];
        },
     
        isFocusable: function ContextualTabWebPart_CustomPageComponent$isFocusable() {
            return true;
        },
        
        canHandleCommand: function ContextualTabWebPart_CustomPageComponent$canHandleCommand(commandId) {
            // Contextual Tab commands
            if ((commandId === 'CustomContextualTab.EnableCustomTab') || (commandId === 'CustomContextualTab.EnableCustomGroup') || (commandId === 'CustomContextualTab.HelloWorldCommand') || (commandId === 'CustomContextualTab.GoodbyeWorldCommand')) {
                return true;
            }
        },
     
        handleCommand: function ContextualTabWebPart_CustomPageComponent$handleCommand(commandId, properties, sequence) {
     
            if (commandId === 'CustomContextualTab.HelloWorldCommand') {
                alert('Hello, world!');
            }
            if (commandId === 'CustomContextualTab.GoodbyeWorldCommand') {
                alert('Good-bye, world!');
            }
        },
     
        getId: function ContextualTabWebPart_CustomPageComponent$getId() {
            return this._webPartPageComponentId;
        }
    }
     
     
    ContextualTabWebPart.CustomPageComponent.registerClass('ContextualTabWebPart.CustomPageComponent', CUI.Page.PageComponent);
    SP.SOD.notifyScriptLoadedAndExecuteWaitingJobs("CustomContextualTabPageComponent.js");
    

部署自定义项

项目将由 Visual Studio 2010 中的 SharePoint 开发工具自动部署。作为部署过程的一部分,应用程序池自动重置。

部署 Web 部件

  1. 按 F5。Visual Studio 2010 中的 SharePoint 开发工具将自动构建并部署 Web 部件和 JavaScript 文件。

  2. 导航至您的网站。

  3. 单击"编辑"按钮。

  4. 在"插入"选项卡中,单击"Web 部件"按钮。

  5. 在"Web 部件添加器"中,选择"自定义"类别。

  6. 在 Web 部件列表中,选择"ContextualTabWebPart",然后单击"添加"。

  7. 该 Web 部件添加到页面后,单击"ContextualTabWebPart"Web 部件。

  8. 请注意显示的"自定义上下文选项卡组"选项卡。

请参阅

概念

服务器功能区 XML

开发服务器功能区的网页组件

服务器功能区的命令性自定义项

服务器功能区的声明性自定义项