1. 程式人生 > >SharePoint2010 新增帶自定義屬性的WebPart

SharePoint2010 新增帶自定義屬性的WebPart

一、新建一個webPart

我們在工程裡新建一個名為WebPartWithAttribute的視覺化部件

二、增加自定義屬性

在新建的webpart裡找到WebPartWithAttribute.cs檔案。在裡面新增如下程式碼:

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable, Category("DB Connection"),
        WebDisplayName("DB Connection String"),
        WebDescription("DB Connection string.")]
        public string DBConnectionString { get; set; }

我們看到其中幾個字串,作用如下圖:

 

可以根據上圖對照,就知道意思了。

三、接下來要做的東東

好了,我們已經添加了一個名為DBConnectionString的屬性值。現在開啟這個webpart的後置程式碼WebPartWithAttributeUserControl.ascx.cs檔案,並新增如下程式碼:

public WebPartWithAttribute WebPartObj { get; set; }
然後我們回到WebPartWithAttribute.cs,並修改CreateChildControls()方法為如下:
        protected override void CreateChildControls()
        {
            WebPartWithAttributeUserControl control = Page.LoadControl(_ascxPath) as WebPartWithAttributeUserControl;
            if (control != null)
                control. = this;
            Controls.Add(control);
        }

好了,我們來測試一下:

我在頁面上建了一個Lable,並在page_WebPartObjload中把DBConnectingString的值給他:

ASPxLabel1.Text = WebPartObj.DBConnectionString;
部署並插入webpart到頁面,在webpart的設定屬性頁面的下方找到我們的自定義屬性,並填上值:


然後點確定,並重新整理頁面:


大功告成!來瓶啤酒!

---------------------------------------------------華麗的分割線--------------------------------------------------

發現一個問題,如果我想要加一個下拉列表腫麼辦?

很簡單,用一個列舉解決問題:

        [Personalizable(PersonalizationScope.Shared),
        WebBrowsable, Category("DB Connection"),
        WebDisplayName("DB Connection String"),
        WebDescription("DB Connection string.")]
        public DBTest DBConnectionString { get; set; }
        public enum DBTest
        {
            測試1 = 0,
            測試2,
            測試3
        };
哇塞,又成功了!



這裡是一個數據型別和引數顯示方式的對應表

Boolean  Check box
String  Text box
Integer  Text box
DateTime  Text box
Enum  Drop-down list