首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

使用 Visual Studio 建立自訂 Web Part 屬性完整教學

     編輯:關於.NET

自訂屬性能讓 Web Part 擁有額外的設定選項,使用者可在屬性窗格中調整行為,無需修改程式碼。本文示範如何用 Visual Studio 建立包含自訂屬性的 Web Part。

專案建立流程

  1. 開啟 Visual Studio,建立 空白 SharePoint 專案,命名為 CustomWPProperties,部署為 場方案。
  2. 在專案上按右鍵 → 新增 → 新項目,選擇 Web Part,命名為 WPPropertyExample。
  3. 右鍵點擊 WPPropertyExample.cs 選擇 檢視程式碼。
  4. 在類別中加入以下程式碼,定義一個列舉型別屬性並套用屬性標記:
using System;
using System.ComponentModel;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;

namespace CustomWPProperties.WPPropertyExample
{
    public class WPPropertyExample : WebPart
    {
        Label lblTitle = new Label();

        public enum SharePointLists { Stats, Products, Customers }

        protected SharePointLists listOfList;

        [Personalizable(PersonalizationScope.User),
         WebBrowsable,
         WebDisplayName("可用清單"),
         WebDescription("SharePoint 站點中的可用清單。")]
        public SharePointLists MySticks
        {
            get { return listOfList; }
            set { listOfList = value; }
        }

        protected override void CreateChildControls()
        {
            lblTitle.Text = "擁有自訂屬性的 Web Part";
            this.Controls.Add(lblTitle);
        }
    }
}
  1. 按 建置 → 部署方案。
  2. 在 SharePoint 站點:網站操作 → 編輯頁面 → 新增 Web 組件,在 Custom 類別中選取 WPPropertyExample 加入。
  3. 編輯該 Web Part,屬性窗格即會出現 可用清單 下拉選單,含 Stats、Products、Customers 三個選項。

Web Part 屬性窗格示意圖

重點說明

  • Personalizable:讓屬性值能依使用者個人化儲存。
  • WebBrowsable:使屬性出現在屬性窗格中。
  • WebDisplayName / WebDescription:提供友善的顯示名稱與說明。

透過這樣的方式,您可以輕鬆為 Web Part 增加靈活的設定選項,提升使用者體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved