WebPart 代码开发
假定你是使用WebPart Library进行开发的。
(一)定义Toolbox data
设置类的属性值。在类声明前加上对该类的属性设置。
[ToolboxData("<{0}:WebPart1 runat=server></{0}:WebPart1>")] // 注意其中Target的定义与类名相同 public class WebPart1 : Microsoft.SharePoint.WebPartPages.WebPart{ … } |
(二)定义XML namespace
如果想成功导入用户自定义WebPart,你必须为每一个WebPart设置XML namespace属性。这个动作是在Web Part Class 定义的时候完成的。
[XmlRoot(Namespace="MyWebParts")] |
(三)逻辑实现
//-------------------------------------------------------------------- // File: SimpleWebPart.cs // // Purpose: A sample Web Part that demonstrates how to create a basic // Web Part. //-------------------------------------------------------------------- using System; using System.ComponentModel; using System.Runtime.InteropServices; using System.Web.UI; using System.Web.UI.WebControls; using System.Xml.Serialization; using Microsoft.SharePoint; using Microsoft.SharePoint.WebPartPages; using Microsoft.SharePoint.Utilities; using System.Web.UI.HtmlControls; namespace MyWebParts { ///<summary> /// This Web Part changes it's own title and implements a custom property. ///</summary> [XmlRoot(Namespace="MyWebParts")] public class SimpleWebPart : WebPart { private const string defaultText = "hello"; private string text=defaultText; // Declare variables for HtmlControls user interface elements. HtmlButton _mybutton; HtmlInputText _mytextbox; // Event handler for _mybutton control that sets the // Title property to the value in _mytextbox control. public void _mybutton_click (object sender, EventArgs e) { this.Title = _mytextbox.Value; try { this.SaveProperties=true; } catch { Caption = "Error... Could not save property."; } } // Override the ASP.NET Web.UI.Controls.CreateChildControls // method to create the objects for the Web Part's controls. protected override void CreateChildControls () { // Create _mytextbox control. _mytextbox = new HtmlInputText(); _mytextbox.Value=""; Controls.Add(_mytextbox); // Create _mybutton control and wire its event handler. _mybutton = new HtmlButton(); _mybutton.InnerText = "Set Web Part Title"; _mybutton.ServerClick += new EventHandler (_mybutton_click); Controls.Add (_mybutton); } [Browsable(true),Category("Miscellaneous"), DefaultValue(defaultText), WebPartStorage(Storage.Personal), FriendlyName("Text"),Description("Text Property")] public string Text { get { return text; } set { text = value; } }
protected override void RenderWebPart(HtmlTextWriter output) { RenderChildren(output); // Securely write out HTML output.Write("<BR>Text Property: " + SPEncode.HtmlEncode(Text)); } } } |
注意:默认情况下,信认级别设置成WSS_Minimal,它不能访问SharePoint object model。为了能设置 SaveProperties 属性,你必须执行下面三个动作。
a) Create a custom policy file for your assembly.
b) Install your assembly in the global assembly cache.
c) Increase the trust level for the entire virtual server.