Share via


演练:本地化 Web 部件

上次修改时间: 2010年12月7日

适用范围: SharePoint Foundation 2010

本文内容
创建空白 SharePoint 项目
创建 Web 部件
添加语言资源
本地化功能和 Web 部件控件说明文件
编写代码来检索本地化字符串
本地化 Web 部件属性
本地化属性
测试 Web 部件

本演练演示如何本地化要部署在 Microsoft SharePoint Foundation 2010 上的 Web 部件。本演练中使用的技术特定于 SharePoint Foundation 2010。它们不适用于部署在 Microsoft ASP.NET 上的 Web 部件。

在本演练中,您将创建可使用多种语言显示文本"Hello, world"的简单 Web 部件。另外,本演练还演示如何准备对与该 Web 部件相关的所有显示文本进行本地化,包括以下各项的显示文本:

  • 设置 Web 部件的功能。

  • Web 部件库中 Web 部件的条目。

  • Web 部件版式中的标题。

  • Web 部件菜单上的自定义操作。

  • Web 部件编辑器中的自定义属性。

  • Web 部件承载的子控件。

先决条件

本演练中的过程是为使用 Microsoft Visual Studio 2010 的开发人员编写的。有关必备组件,请参阅开发 SharePoint 解决方案的要求(该链接可能指向英文页面)

若要完成本演练,您需要:

有关在 SharePoint Foundation 2010 中本地化解决方案的重要概念介绍,请参阅了解多语言用户界面 (MUI)

创建空白 SharePoint 项目

首先在 Visual Studio 2010 中创建一个空白 SharePoint 项目。将该项目命名为"Wingtip.WebParts"。配置该项目以将其部署为服务器场解决方案。

备注

可以将您在本演练中创建的 Web 部件部署为沙盒解决方案。该 Web 部件的所有代码均可以在部分信任模式下运行。不过,除了 Web 部件外,本演练还将语言资源文件部署到 SharePoint 安装中的根文件夹,而项目的此部分需要完全信任。在生产环境中,您可能希望使用两个单独的解决方案:用于部署 Web 部件的沙盒解决方案和用于部署资源文件的服务器场解决方案。为简便起见,本演练只使用一个服务器场解决方案。

创建空白 SharePoint 项目

  1. 以管理员身份启动 Visual Studio 2010。

  2. 指向"文件"菜单上的"新建",然后单击"新建项目",以打开"新建项目"对话框。

  3. 展开"Visual C#"或"Visual Basic"下的"SharePoint"节点,然后单击"2010"。

  4. 在"模板"窗格中,单击"空白 SharePoint 项目",将该项目的名称更改为 Wingtip.WebParts,然后单击"确定"。

    将显示"SharePoint 自定义向导"。

  5. 在"指定用于调试的网站和安全级别"页上,输入要向其中添加新 Web 部件的 SharePoint 网站的 URL,或使用默认位置(http://<系统名称>/)。

  6. 在"此 SharePoint 解决方案的信任级别是什么?"部分,选择"部署为场解决方案"。

  7. 单击"完成"。

    该项目将显示在"解决方案资源管理器"中。

创建 Web 部件

下一个任务是在项目中添加 Web 部件。为此,需创建一个派生自 System.Web.UI.WebControls.WebParts 命名空间中的 WebPart 类的新类。示例 Web 部件将重写 CreateChildControls 方法以添加子控件(Label 类的实例)。在本演练的稍后部分,您将了解如何本地化此控件显示的文本。为使您有机会本地化 Web 部件可以具有的所有不同类型的用户界面 (UI),示例代码将创建一个具有 WebBrowsable 和 Personalizable 属性 (Attribute) 的自定义属性 (Property)。这些属性 (Attribute) 会使属性 (Property) 在用户编辑 Web 部件时显示在工具窗格中。最后,示例通过创建自定义 WebPartVerb 向 Web 部件选项菜单中添加一项。

在项目中添加 Web 部件

  1. 在"解决方案资源管理器"中,选择"Wingtip.WebParts"节点。在"项目"菜单上单击"添加新项"。

  2. 在"添加新项"对话框中,选择"Web 部件"。在"名称"字段中,键入 LocalizedWebPart。然后单击"添加"。

    将在代码编辑器中打开 LocalizedWebPart 类。

  3. 在代码编辑器中,按 Ctrl+A 全选。然后复制并粘贴以下代码:

    using System;
    using System.ComponentModel;
    using System.Globalization;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using Microsoft.SharePoint.WebControls;
    
    namespace Wingtip.WebParts.LocalizedWebPart
    {
        [ToolboxItemAttribute(false)]
        public class LocalizedWebPart : WebPart
        {
    
            // Constants for display strings.
            const string CATEGORY_TEXT = "Text";
            const string LABEL_TEXT = "Hello, world!";
            const string TOOLPANE_BOLD = "Bold";
            const string TOOLPANE_BOLD_DESC = "Make the text bold";
            const string VERB_UNDERLINE = "Underline";
            const string VERB_UNDERLINE_DESC = "Draw a line under the text";
            const string WEB_PART_TITLE = "Localized Web Part";
            const string WEB_PART_DESC = "An example localized Web Part";
    
            // Member variable for the child control.
            private Label m_textLabel;
    
            // Instantiates the Web Part.
            public LocalizedWebPart()
            {
    
                // Add a handler for the PreRender event.
                PreRender += LocalizedWebPart_PreRender;
            }
    
            // Creates the control tree.
            protected override void CreateChildControls()
            {
    
                // Add a Label control to display content.
                m_textLabel = new Label();
                m_textLabel.Text = Text;
                Controls.Add(m_textLabel);
            }
    
            // The PreRender event is raised after the Web Part is edited,
            // so this is a good time to update the child control.
            void LocalizedWebPart_PreRender(object sender, EventArgs e)
            {
    
                // Make sure that CreateChildControls has been called.
                EnsureChildControls();
    
                // Apply current Web Part settings to the child control.
                m_textLabel.Font.Bold = Bold;
            }
    
    
            // Indicates whether the text is bold.
            // This property is exposed in the Web Part Editor.
            [WebBrowsable]
            [Personalizable(PersonalizationScope.Shared)]
            [Category(CATEGORY_TEXT)]
            [WebDisplayName(TOOLPANE_BOLD)]
            [WebDescription(TOOLPANE_BOLD_DESC)]
            public bool Bold { get; set; }
    
            // Overrides the Description property.
            [WebBrowsable(false), Personalizable(false)]
            public override string Description
            {
                get { return WEB_PART_DESC; }
                set { ; }
            }
    
            // Gets the text to display.
            private string Text
            {
                get { return LABEL_TEXT; }
            }
    
            // Overrides the Title property.
            [WebBrowsable(false), Personalizable(false)]
            public override string Title
            {
                get { return WEB_PART_TITLE; }
                set { ; }
            }
    
            // Gets a collection of custom verbs that provide items
            // on the options menu for the Web Part.
            public override WebPartVerbCollection Verbs
            {
                get
                {
    
                    // Add a custom verb to toggle underlining for the text.
                    WebPartVerb verb = new WebPartVerb(this.ID + "_UnderlineVerb",
                     (sender, args) =>
                     {
                         EnsureChildControls();
                         m_textLabel.Font.Underline = !m_textLabel.Font.Underline;
                     });
    
                    verb.Checked = m_textLabel.Font.Underline;
                    verb.Text = VERB_UNDERLINE;
                    verb.Description = VERB_UNDERLINE_DESC;
    
                    WebPartVerb[] newVerbs = new WebPartVerb[] { verb };
                    return new WebPartVerbCollection(base.Verbs, newVerbs);
                }
            }
        }
    }
    
    Imports System
    Imports System.ComponentModel
    Imports System.Globalization
    Imports System.Web.UI.WebControls
    Imports System.Web.UI.WebControls.WebParts
    Imports Microsoft.SharePoint.WebControls
    
    <ToolboxItemAttribute(false)> _
    Public Class LocalizedWebPart
        Inherits WebPart
    
        ' Constants for display strings.
        Const CATEGORY_TEXT As String = "Text"
        Const LABEL_TEXT As String = "Hello, world!"
        Const TOOLPANE_BOLD As String = "Bold"
        Const TOOLPANE_BOLD_DESC As String = "Make the text bold"
        Const VERB_UNDERLINE As String = "Underline"
        Const VERB_UNDERLINE_DESC As String = "Draw a line under the text"
        Const WEB_PART_TITLE As String = "Localized Web Part"
        Const WEB_PART_DESC As String = "An example localized Web Part"
    
        ' Member variable for the child control.
        Private m_textLabel As Label
    
        ' Instantiates the Web Part.
        Public Sub New()
            ' Add a handler for the PreRender event.
            AddHandler PreRender, AddressOf LocalizedWebPart_PreRender
        End Sub
    
        ' Creates the control tree.
        Protected Overrides Sub CreateChildControls()
            ' Add a Label control to display content.
            m_textLabel = New Label()
            m_textLabel.Text = Text
            Controls.Add(m_textLabel)
        End Sub
    
        ' The PreRender event is raised after the Web Part is edited,
        ' so this is a good time to update the child control.
        Private Sub LocalizedWebPart_PreRender(ByVal sender As Object, ByVal e As EventArgs)
    
            ' Make sure that CreateChildControls has been called.
            EnsureChildControls()
    
            ' Apply current Web Part settings to the child control.
            m_textLabel.Font.Bold = Bold
        End Sub
    
        Private m_bold As Boolean
    
        ' Indicates whether the text is bold.
        ' This property is exposed in the Web Part Editor.
        <WebBrowsable()> _
        <Personalizable(PersonalizationScope.[Shared])> _
        <Category(CATEGORY_TEXT)> _
        <WebDisplayName(TOOLPANE_BOLD)> _
        <WebDescription(TOOLPANE_BOLD_DESC)> _
        Public Property Bold() As Boolean
            Get
                Return m_bold
            End Get
            Set(ByVal value As Boolean)
                m_bold = value
            End Set
        End Property
    
        ' Overrides the Description property.
        <WebBrowsable(False)> _
        <Personalizable(False)> _
        Public Overrides Property Description As String
            Get
                Return WEB_PART_DESC
            End Get
            Set(ByVal value As String)
            End Set
        End Property
    
        ' Gets the text to display.
        ReadOnly Property Text As String
            Get
                Return LABEL_TEXT
            End Get
        End Property
    
        ' Overrides the Title property.
        <WebBrowsable(False)> _
        <Personalizable(False)> _
        Public Overrides Property Title As String
            Get
                Return WEB_PART_TITLE
            End Get
            Set(ByVal value As String)
            End Set
        End Property
    
        ' Gets a collection of custom verbs that provide items
        ' on the options menu for the Web Part.
        Public Overrides ReadOnly Property Verbs() As WebPartVerbCollection
            Get
    
                ' Add a custom verb to toggle underlining for the text.
                Dim verb As New WebPartVerb(Me.ID + "_UnderlineVerb", AddressOf UnderlineVerbHandler)
    
                verb.Checked = m_textLabel.Font.Underline
                verb.Text = VERB_UNDERLINE
                verb.Description = VERB_UNDERLINE_DESC
    
                Dim newVerbs As WebPartVerb() = New WebPartVerb() {verb}
                Return New WebPartVerbCollection(MyBase.Verbs, newVerbs)
            End Get
        End Property
    
        ' Toggles underlining.
        Private Sub UnderlineVerbHandler(ByVal sender As Object, ByVal args As EventArgs)
            EnsureChildControls()
            m_textLabel.Font.Underline = Not m_textLabel.Font.Underline
        End Sub
    
    End Class
    
  4. 按 Ctrl+Shift+S 全部保存。

现在您具有一个有效的 Web 部件,测试它。按 F5 生成并部署解决方案。当网站打开后,创建一个新的 Web 部件页并将您的 Web 部件添加到其中。在网页处于编辑模式下时,检查 Web 部件版式右上角的选项菜单。多次单击"下划线"以确认自定义动词起作用。然后单击"编辑 Web 部件"。当显示工具窗格时,在该窗格的底部查找自定义属性。选择"加粗",然后单击"应用"来确认属性设置正确无误。

添加语言资源

本地化 Web 部件的第一步是向项目中添加语言资源文件。对于本演练,您只需要两个资源文件:一个用于网站默认语言的文件以及一个用于网站支持的备用语言之一的文件。您可以使用您喜欢的任何语言。示例使用英语和西班牙语。

提示提示

若要查找您的开发网站支持的语言,请在浏览器中打开网站主页。单击"网站操作",然后单击"网站设置"。在"网站管理"下,单击"语言设置"。默认语言列在页面顶部。备用语言列在默认语言之下。

您必须将创建的资源文件部署到 Web 服务器的文件系统中可由生成显示文本的 Web 部件的所有组件访问的位置,这些组件包括:

您可以采用多种备选方法来在目标 Web 服务器上设置语言资源。最简单的方法和以后可以最灵活地为其他语言添加支持的方法是设置紧接 SharePoint Foundation 安装根之下的 Resources 文件夹中的语言资源文件。Visual Studio 用于此文件夹的标记是 {SharePointRoot}\Resources。完整路径是 %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\Resources。SharePoint Foundation 将内置 Web 部件所使用的语言资源安装在此文件夹中。

向 {SharePointRoot}\Resources 文件夹中添加资源

  1. 在"解决方案资源管理器"中,选择"Wingtip.Webparts"项目节点。在"项目"菜单上单击"添加 SharePoint 映射文件夹"。

  2. 在"添加 SharePoint 映射文件夹"对话框中,选择"Resources",然后单击"确定"。

    Resources 文件夹将添加到项目中。检查此文件夹的属性。请注意,DeploymentLocation 属性设置为 {SharePointRoot}\Resources。

  3. 在"解决方案资源管理器"中,选择"Resources"文件夹。在"项目"菜单上单击"添加新项"。

  4. 在"添加新项"对话框中,展开"Visual C#"(如果您的开发语言是 C#)或"常用项"(如果您在 Visual Basic 中工作)的节点。选择"常规"。在模板窗格中,选择"资源文件"。将文件命名为 Wingtip.WebParts.resx,然后单击"添加"。

    资源文件将添加到项目中并在"托管资源编辑器"中打开。

    提示提示

    当您设置全局 Resources 文件夹中的文件时,最好选择唯一的文件名以避免与其他应用程序设置的资源产生命名冲突。一个约定是使用您的公司名称作为文件名前缀。例如,如果您的公司是 Wingtip Toys,则您部署的资源文件的名称可以全部以"Wingtip"开头。

  5. 在"解决方案资源管理器"中,右键单击您刚才创建的资源文件,然后单击"打开方式"。在"打开方式"对话框中选择"XML (文本)编辑器",然后单击"确定"。

    将在编辑器中打开此资源文件。

  6. 向下滚动到文件底部。在 </root> 标记的紧上方插入一个空行。复制以下标记并将其粘贴到文件中的插入点。

      <data name="Bold" xml:space="preserve">
        <value>Bold (invariant)</value>
      </data>
      <data name="BoldDesc" xml:space="preserve">
        <value>Make the text bold (invariant)</value>
      </data>
      <data name="FeatureDesc" xml:space="preserve">
        <value>An example localized Web Part (invariant)</value>
      </data>
      <data name="FeatureTitle" xml:space="preserve">
        <value>Localized Web Part (invariant)</value>
      </data>
      <data name="LabelText" xml:space="preserve">
        <value>Hello, world! (invariant)</value>
      </data>
      <data name="TextCategory" xml:space="preserve">
        <value>Text (invariant)</value>
      </data>
      <data name="Underline" xml:space="preserve">
        <value>Underline (invariant)</value>
      </data>
      <data name="UnderlineDesc" xml:space="preserve">
        <value>Draw a line under the text (invariant)</value>
      </data>
      <data name="WebPartDesc" xml:space="preserve">
        <value>An example localized Web Part (invariant)</value>
      </data>
      <data name="WebPartTitle" xml:space="preserve">
        <value>Localized Web Part (invariant)</value>
      </data>
    
  7. 按 Ctrl+S 保存文件。然后在"文件"菜单上单击"关闭"以关闭此文件。

  8. 在"解决方案资源管理器"中,选择文件 Wingtip.WebParts.resx。在"编辑"菜单上,单击"复制"。然后单击"粘贴"。

    名为"Wingtip.WebParts.resx 副本"的文件将添加到 Resources 文件夹中。

  9. 右键单击名为"Wingtip.WebParts.resx 副本"的文件,然后单击"重命名"。将文件重命名为 Wingtip.WebParts.语言-国家/地区.resx,其中语言 是您的网站的默认语言的两个字母组成的代码,国家/地区 是子区域性的两个字母组成的代码。

    例如,如果默认语言是英语(美国),则资源文件名为 Wingtip.WebParts**.en-US**.resx。

    有关语言标识符的详细信息,请参阅 System.Globalization.CultureInfo 类。

    重要注释重要信息

    正如本演练中稍后所演示的,通过使用资源文件的基文件名(例如"Wingtip.WebParts")可引用此资源文件。当 SharePoint Foundation 检索资源值时,它会查找此基文件名后跟与当前执行线程的 CurrentUICulture 属性值对应的语言标识符的资源文件。SharePoint Foundation 期望找到精确匹配项。例如,如果当前线程的语言标识符为"pt-BR",则 SharePoint Foundation 会查找名为"基文件名.pt-BR.resx"的资源文件。它会忽略具有相同语言代码但子区域性不同的文件,例如"基文件名.pt.resx"和"基文件名.pt-PT.resx"。

    如果 SharePoint Foundation 找不到与执行线程的语言标识符匹配的资源文件,则查找回退 资源文件。回退的第一个选择是固定区域性的资源文件,即文件名末尾没有任何语言标识符的资源文件。例如,在当前项目中,固定区域性的资源文件是 Wingtip.WebParts.resx。如果 SharePoint Foundation 无法找到固定区域性的资源文件,它会尝试回退到默认语言。如果它找不到默认语言的资源文件,则会显示资源名称。

  10. 重复步骤 8 和 9,此次为您的网站上启用的备用语言追加语言标识符。

  11. 打开您刚才创建的两个区域性特定的语言资源文件,并将单词"invariant"替换为文件的语言标识符。例如,在 Wingtip.WebParts.en-US.resx 中,"Bold (invariant)"将变成"Bold (en-US)"。

    对于本演练,无需翻译字符串值。只需为未翻译的字符串追加语言标识符。在测试 Web 部件时,语言标识符可指示显示的语言。

  12. 按 Ctrl+Shift+S 全部保存。

本地化功能和 Web 部件控件说明文件

下一个主要任务是本地化两个关键 XML 文件中出现的显示字符串:Feature 元素文件和 Web 部件控件说明(该链接可能指向英文页面)文件。这两个文件包含您可以使用符合以下模式的 ASP.NET 表达式替换的标题和说明字符串:

$Resources:BaseFileName,ResourceName

美元符号 ($) 指示后面是表达式。前缀"Resources"指示表达式的类型。冒号 (:) 后面的后缀是要解析的表达式值。此值的第一部分是资源文件的基文件名。逗号后面的部分是要从文件中检索的本地化字符串的名称。表达式中的任何位置都不允许空格。

备注

您可能会看到以分号 (;) 结尾的资源表达式。此分隔符可接受,但 SharePoint Foundation 2010 不需要它。

本地化功能

  1. 在"解决方案资源管理器"中,展开 Features 文件夹,然后双击"Feature1"。

    将在"功能设计器"中打开 Feature1.feature。

  2. 在"功能设计器"中,删除"标题"框中的文本,并使用以下资源表达式替换它:

    $Resources:Wingtip.WebParts,FeatureTitle
    
  3. 将以下表达式粘贴到"说明"框中:

    $Resources:Wingtip.WebParts,FeatureDesc
    
  4. 按 Ctrl+Shift+S 全部保存。

本地化 Web 部件控件说明

  1. 在"解决方案资源管理器"中,展开 LocalizedWebPart 文件夹,然后双击 LocalizedWebPart.webpart。

    将在 XML 编辑器中打开 LocalizedWebPart.webpart。

  2. 删除 Title 属性的值("LocalizedWebPart"),并使用以下资源表达式替换它:

    $Resources:Wingtip.WebParts,WebPartTitle
    
  3. 删除 Description 属性的值("My WebPart"),并使用以下资源表达式替换它:

    $Resources:Wingtip.WebParts,WebPartDesc
    
  4. 按 Ctrl+Shift+S 全部保存。

编写代码来检索本地化字符串

通过将语言资源嵌入与主程序集一起部署到全局程序集缓存中的附属程序集,您可以本地化普通 ASP.NET 应用程序中的代码。当您的代码需要检索资源值时,可调用 HttpContext.GetGlobalResourceObject 方法。

虽然您确实可以从 SharePoint Foundation 上运行的代码调用此方法,但为 SharePoint Foundation 开发人员提供了替代方法,此方法不要求您将语言资源部署到附属程序集中。SPUtility 类包括静态方法 GetLocalizedString,它可从位于 Web 服务器上 {SharePointRoot}\Resources 文件夹中的资源文件检索字符串值。在本演练中,您将使用 GetLocalizedString 方法。

GetLocalizedString 方法需要第一个参数中的资源表达式和第二个参数中资源文件的基文件名。为简化从您的 Web 部件代码进行的方法调用,可将 GetLocalizedString 包装在您自己设计的方法中。

创建检索资源字符串的方法

  1. 在"解决方案资源管理器"中,选择"Wingtip.Webparts"项目节点。在"项目"菜单上单击"添加类"。

    将显示"添加新项"对话框。

  2. 在"名称"字段中,键入 Utility.cs 或 Utility.vb,具体取决于您的语言。然后单击"添加"。

  3. 按 Ctrl+A 全选。然后复制并粘贴以下代码,以替换文件的当前内容。

    using Microsoft.SharePoint.Utilities;
    
    namespace Wingtip.WebParts.LocalizedWebPart
    {
        public static class Utility
        {
    
            // Wraps the SPUtility method of the same name.
            public static string GetLocalizedString(string resourceName, int LCID)
            {
                if (string.IsNullOrEmpty(resourceName))
                    return string.Empty;
    
                // SPUtility.GetLocalized string needs a resource expression as the first argument.
                string resourceExpression = string.Format("$Resources:{0}", resourceName);
    
                string resourceFile = "Wingtip.WebParts";
    
                // Note: If the named resource does not have a value for the specified language, 
                // SPUtility.GetLocalizedString returns the value for the invariant language.
                // If the named resource does not exist, it returns the original expression.
               return SPUtility.GetLocalizedString(resourceExpression, resourceFile, (uint)LCID);
            }
        }
    }
    
    Imports Microsoft.SharePoint.Utilities
    
    Public NotInheritable Class Utility
    
        ' Wraps the SPUtility method of the same name.
        Public Shared Function GetLocalizedString(ByVal resourceName As String, ByVal LCID As Integer) As String
    
            If String.IsNullOrEmpty(resourceName) Then
                Return String.Empty
            End If
    
            Dim resourceFile As String = "Wingtip.WebParts"
    
            ' SPUtility.GetLocalized string needs a resource expression as the first argument.
            Dim resourceExpression As String = String.Format("$Resources:{0}", resourceName)
    
            ' Note: If the named resource does not have a value for the specified language, 
            ' SPUtility.GetLocalizedString returns the value for the invariant language.
            ' If the named resource does not exist, it returns the original expression.
            Return SPUtility.GetLocalizedString(resourceExpression, resourceFile, CUInt(LCID))
    
        End Function
    
    End Class
    
  4. 按 Ctrl+Shift+S 全部保存。

本地化 Web 部件属性

下一个任务是本地化返回显示文本的 Web 部件属性的代码。在每种情况下,您都可以将硬编码的字符串替换为对实用程序方法 GetLocalizedString 的调用,以便传递资源名称和当前线程的语言的区域设置 ID (LCID)。您可以通过访问静态属性 CultureInfo.CurrentUICulture 来获取当前语言的 LCID。

本地化 Web 部件的属性

  1. 在"解决方案资源管理器"中,双击 LocalizedWebPart.cs 或 LocalizedWebPart.vb 来打开源文件。

  2. 在文件顶部,紧接 LocalizedWebPart 类的声明之下是多个字符串常量的声明。删除这些声明并使用以下代码替换它们:

    // Translate resource keys to string constants.
    const string CATEGORY_TEXT = "TextCategory";
    const string LABEL_TEXT = "LabelText";
    const string TOOLPANE_BOLD = "Bold";
    const string TOOLPANE_BOLD_DESC = "BoldDesc";
    const string VERB_UNDERLINE = "Underline";
    const string VERB_UNDERLINE_DESC = "UnderlineDesc";
    const string WEB_PART_TITLE = "WebPartTitle";
    const string WEB_PART_DESC = "WebPartDesc";
    
    ' Translate resource keys to string constants.
    Const CATEGORY_TEXT As String = "TextCategory"
    Const LABEL_TEXT As String = "LabelText"
    Const TOOLPANE_BOLD As String = "Bold"
    Const TOOLPANE_BOLD_DESC As String = "BoldDesc"
    Const VERB_UNDERLINE As String = "Underline"
    Const VERB_UNDERLINE_DESC As String = "UnderlineDesc"
    Const WEB_PART_TITLE As String = "WebPartTitle"
    Const WEB_PART_DESC As String = "WebPartDesc"
    
  3. 导航到 Description 属性。使用以下代码替换 get 取值函数的代码:

    get { return Utility.GetLocalizedString(WEB_PART_DESC, CultureInfo.CurrentUICulture.LCID); }
    
    Get
        Return Utility.GetLocalizedString(WEB_PART_DESC, CultureInfo.CurrentUICulture.LCID)
    End Get
    
  4. 导航到 Text 属性。使用以下代码替换 get 取值函数的代码:

    get { return Utility.GetLocalizedString(LABEL_TEXT, CultureInfo.CurrentUICulture.LCID); }
    
    Get
        Return Utility.GetLocalizedString(LABEL_TEXT, CultureInfo.CurrentUICulture.LCID)
    End Get
    
  5. 导航到 Title 属性。使用以下代码替换 get 取值函数的代码:

    get { return Utility.GetLocalizedString(WEB_PART_TITLE, CultureInfo.CurrentUICulture.LCID); }
    
    Get
        Return Utility.GetLocalizedString(WEB_PART_TITLE, CultureInfo.CurrentUICulture.LCID)
    End Get
    
  6. 导航到 Verbs 属性。使用以下行替换设置 verb.Text 和 verb.Description 属性的两行代码:

    verb.Text = Utility.GetLocalizedString(VERB_UNDERLINE, CultureInfo.CurrentUICulture.LCID);
    verb.Description = Utility.GetLocalizedString(VERB_UNDERLINE_DESC, CultureInfo.CurrentUICulture.LCID);
    
    verb.Text = Utility.GetLocalizedString(VERB_UNDERLINE, CultureInfo.CurrentUICulture.LCID)
    verb.Description = Utility.GetLocalizedString(VERB_UNDERLINE_DESC, CultureInfo.CurrentUICulture.LCID)
    
  7. 按 Ctrl+Shift+S 全部保存。

本地化属性

Web 部件的代码定义具有多个属性 (Attribute) 的自定义 Bold 属性 (Property),如以下片段中所示:

[WebBrowsable]
[Personalizable(PersonalizationScope.Shared)]
[Category(CATEGORY_TEXT)]
[WebDisplayName(TOOLPANE_BOLD)]
[WebDescription(TOOLPANE_BOLD_DESC)]
public bool Bold { get; set; }
<WebBrowsable()> _
<Personalizable(PersonalizationScope.[Shared])> _
<Category(CATEGORY_TEXT)> _
<WebDisplayName(TOOLPANE_BOLD)> _
<WebDescription(TOOLPANE_BOLD_DESC)> _
Public Property Bold() As Boolean
    Get
        Return m_bold
    End Get
    Set(ByVal value As Boolean)
        m_bold = value
    End Set
End Property

WebBrowsable 和 Personalizable 属性 (Attribute) 使属性 (Property) 在用户编辑 Web 部件时显示在编辑用户 UI 中。其他三个属性为编辑 UI 提供显示文本:

  • Category

    提供属性的自定义类别的显示名称。

  • WebDisplayName

    提供属性的显示名称。

  • WebDescription

    提供属性的工具提示的文本。

若要本地化这些属性的文本,您必须编写派生自 CategoryAttribute 类、WebDisplayNameAttribute 类和 WebDescriptionAttribute 类的自定义属性类。

本地化 Category、WebDisplayName 和 WebDescription 属性

  1. 在"解决方案资源管理器"中,双击 LocalizedWebPart.cs 或 LocalizedWebPart.vb 来打开源文件。

  2. 在 LocalizedWebPart 类的底部,但仍在该类中,插入以下子类的代码:

    public sealed class LocalizedCategoryAttribute : CategoryAttribute
    {
        public LocalizedCategoryAttribute(string category)
            : base(category)
        { }
    
        // Override this method to return values from the webpart's resource file.
        protected override string GetLocalizedString(string value)
        {
            return Utility.GetLocalizedString(value, CultureInfo.CurrentUICulture.LCID);
        }
    }
    
    public sealed class LocalizedWebDisplayNameAttribute : WebDisplayNameAttribute
    {
        bool m_isLocalized;
    
        public LocalizedWebDisplayNameAttribute(string displayName)
            : base(displayName)
        { }
    
        // Override this property to return values from the webpart's resource file.
        public override string DisplayName
        {
            get
            {
                if (!m_isLocalized)
                {
                    this.DisplayNameValue = Utility.GetLocalizedString(base.DisplayName, CultureInfo.CurrentUICulture.LCID);
                    m_isLocalized = true;
                }
                return base.DisplayName;
            }
        }
    }
    
    public sealed class LocalizedWebDescriptionAttribute : WebDescriptionAttribute
    {
        bool m_isLocalized;
    
        public LocalizedWebDescriptionAttribute(string description)
            : base(description)
        { }
    
        // Override this property to return values from the webpart's resource file.
        public override string Description
        {
            get
            {
                if (!m_isLocalized)
                {
                    this.DescriptionValue = Utility.GetLocalizedString(base.Description, CultureInfo.CurrentUICulture.LCID);
                    m_isLocalized = true;
                }
                return base.Description;
            }
        }
    }
    
    Public NotInheritable Class LocalizedCategoryAttribute
        Inherits CategoryAttribute
        Public Sub New(ByVal category As String)
            MyBase.New(category)
        End Sub
    
        ' Override this method to return values from the webpart's resource file.
        Protected Overrides Function GetLocalizedString(ByVal value As String) As String
            Return Utility.GetLocalizedString(value, CultureInfo.CurrentUICulture.LCID)
        End Function
    End Class
    
    Public NotInheritable Class LocalizedWebDisplayNameAttribute
        Inherits WebDisplayNameAttribute
        Private m_isLocalized As Boolean
    
        Public Sub New(ByVal displayName As String)
            MyBase.New(displayName)
        End Sub
    
        ' Override this property to return values from the webpart's resource file.
        Public Overrides ReadOnly Property DisplayName() As String
            Get
                If Not m_isLocalized Then
                    Me.DisplayNameValue = Utility.GetLocalizedString(MyBase.DisplayName, CultureInfo.CurrentUICulture.LCID)
                    m_isLocalized = True
                End If
                Return MyBase.DisplayName
            End Get
        End Property
    End Class
    
    Public NotInheritable Class LocalizedWebDescriptionAttribute
        Inherits WebDescriptionAttribute
        Private m_isLocalized As Boolean
    
        Public Sub New(ByVal description As String)
            MyBase.New(description)
        End Sub
    
        ' Override this property to return values from the webpart's resource file.
        Public Overrides ReadOnly Property Description() As String
            Get
                If Not m_isLocalized Then
                    Me.DescriptionValue = Utility.GetLocalizedString(MyBase.Description, CultureInfo.CurrentUICulture.LCID)
                    m_isLocalized = True
                End If
                Return MyBase.Description
            End Get
        End Property
    End Class
    
  3. 导航到 Bold 属性。然后将 Category、WebDisplayName 和 WebDescription 属性的名称更改为 LocalizedCategory、LocalizedWebDisplayName 和 LocalizedWebDescription。

    不要更改属性参数。修正后的代码如下所示:

    [LocalizedCategory(CATEGORY_TEXT)]
    [LocalizedWebDisplayName(TOOLPANE_BOLD)]
    [LocalizedWebDescription(TOOLPANE_BOLD_DESC)]
    
    <LocalizedCategory(CATEGORY_TEXT)> _
    <LocalizedWebDisplayName(TOOLPANE_BOLD)> _
    <LocalizedWebDescription(TOOLPANE_BOLD_DESC)> _
    
  4. 按 Ctrl+Shift+S 全部保存。

测试 Web 部件

测试 Web 部件以确保它能够正常运行。

测试 Web 部件

  1. 在 Visual Studio 中,按 F5 开始进行调试。

    "输出"窗格将报告生成和部署过程。最后,网站将显示在默认浏览器中。

  2. 单击"网站操作",然后单击"网站设置"。在"网站集管理"下,单击"网站集功能"。确认本地化 Web 部件功能使用默认语言显示标题和说明。

  3. 单击网页右上角中的名称。指向"选择显示语言",然后单击用于本地化 Web 部件的备用语言。确认本地化 Web 部件功能的标题和说明以备用语言显示。

  4. (可选)重复步骤 3,但选择您没有为其部署语言资源文件的语言。确认本地化 Web 部件功能的标题和说明以固定语言显示。

  5. 重复步骤 3,但使语言恢复为网站默认语言。

  6. 单击"网站操作",然后单击"网站设置"。在"库"下,单击"Web 部件"。然后单击"LocalizedWebPart.webpart"。确认标题、说明和示例以默认语言显示。

  7. 重复步骤 3,也可以选择重复步骤 4。确认按预期方式更改了语言。然后使显示恢复为默认语言。

  8. 单击"网站操作",然后单击"其他选项"。单击"网页",选择"Web 部件页",然后单击"创建"。为该页键入名称。然后单击"创建"。

    将显示新的 Web 部件页。

  9. 在"中间栏"中,单击"添加 Web 部件"。在"类别"下,单击"自定义"。选择"LocalizedWebPart",然后单击"添加"。

    备注

    在用户界面的此区域中,Web 部件标题和示例始终以网站默认语言显示。切换到备用语言不会影响 Web 部件显示的文本。

    Web 部件将添加到页面中。

  10. 单击"停止编辑"。切换到备用语言以确认按预期方式更改了 Web 部件标题和标签文本。然后恢复为默认语言。

  11. 将光标移动到页面最右端。当显示向下箭头时,单击它。确认"下划线"操作以默认语言显示在菜单上。

  12. 切换到备用语言。然后重复步骤 11。确认"下划线"操作以备用语言显示。使显示恢复为默认语言。

  13. 将光标移动到页面最右端。当显示向下箭头时,单击它。然后单击"编辑 Web 部件"。在工具窗格的底部,查找"文本"类别。确认名称以默认语言显示。展开此类别。确认"加粗"复选框及其工具提示以默认语言显示。

  14. 切换到备用语言。然后重复步骤 13。确认显示文本更改为备用语言。

请参阅

任务

演练:本地化列、内容类型和列表

引用

CultureInfo

GetLocalizedString

WebBrowsableAttribute

PersonalizableAttribute

CategoryAttribute

WebDisplayNameAttribute

WebDescriptionAttribute

概念

了解多语言用户界面 (MUI)

其他资源

使您的网站用户界面可以使用多种语言(该链接可能指向英文页面)

如何:添加和移除映射文件夹(该链接可能指向英文页面)