相信很多人都在使用用户控件包装器来开发Web Part,原因很简单,创建一个用户控件比直接用代码来写一个Web Part要简单N倍,特别对于界面比较丰富的Web Part而言。引自 KaneBoy:DelegateControl:SharePoint Server 2007内置的一个"用户控件包装器"; 下面是一个继承自System.Web.UI.WebControls.WebParts的WebPart,可以自定义加载的UserControl。
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace Simone.SharePoint.WebPart
{
[XmlRoot(Namespace = "Simone.SharePoint.WebPart")]
public class UserControlWebPart : System.Web.UI.WebControls.WebParts.WebPart
{
public UserControlWebPart()
{
}
private const string defaultText = "";
private string _userControl;
private UserControl _control;
private LiteralControl _child;
[WebBrowsable, Category("用户控件设置"),
DefaultValue(defaultText),
Personalizable(),
FriendlyName("用户控件路径"), Description("请输入用户控件路径 (.ascx)")]
public string UserControl
{
get { return _userControl; }
set { _userControl = value; }
}
protected internal void LoadUserControl()
{
if (!string.IsNullOrEmpty(this._userControl))
{
this._control = (UserControl)Page.LoadControl(this._userControl);
this.Controls.Add(this._control);
}
else
{
this._child = new LiteralControl(string.Format("Web 部件未绑定用户控件。请 <a href=/"javascript:MSOTlPn_ShowToolPaneWrapper('{0}','{1}','{2}');/">打开工具窗格</a> 设置用户控件 URL。例如“~/_CONTROLTEMPLATES/Welcome.ascx”)", 1, 129, this.ID));
this.Controls.Add(this._child);
}
}
protected override void CreateChildControls()
{
base.CreateChildControls();
this.Controls.Clear();
try
{
LoadUserControl();
}
catch (System.Exception ex)
{
this._child = new LiteralControl(string.Format("<b>错误:</b> 不能载入 {0}<br /><b>详细信息:</b> {1}", _userControl, ex.Message));
this.Controls.Add(this._child);
}
}
protected override void Render(HtmlTextWriter writer)
{
EnsureChildControls();
if (_control != null)
{
_control.RenderControl(writer);
}
else
{
_child.RenderControl(writer);
}
}
}
}
效果如下:


一个最基本的框架,陆续增加功能. 请参看:
自定义用户控件的WebPart (二) 为WebPart设置自定义的TollPane PS:下面是我总结的一些东西,没有什么营养。 1、WebPart的自定义属性 * 声明WebPart自定义属性区别
System.Web.UI.WebControls.WebParts.WebPart




Microsoft.SharePoint.WebPartPages.WebPart




* 在ToolPane中显示形式 String -> rendered as a TextBox












Boolean -> rendered as a CheckBox












Enumerators -> rendered as a ComboBox
















来自于:http://www.cnblogs.com/windbell/archive/2008/06/06/1215113.html