SharePoint已经为一般用户和开发者提供了非常好的可重用的能力。更进一步,你可以定义一个可重用的栏定义,这将为我们带来更大的灵活性。
下面是创建一个自定义字段类型的总体步骤:
1.新建SharePoint工程,并添加SharePoint映射文件夹Xml,在Xml的文件名必须以fldtypes_开头,否则不能识别。
2. 添加自定义字段类(RoyCustomField),代码主要重载 protected override void CreateChildControls(),
如果要设置默认值请Override DefaultValue,如果要验证格式是否正确 请Override GetValidatedString
如下:
namespace RoyCustomField{ public class RoyCustomField : SPFieldText { protected TextBox txtField; public RoyCustomField(SPFieldCollection field, string strFieldName) : base(field, strFieldName) { } public RoyCustomField(SPFieldCollection field, string strFieldName, string strDispName) : base(field, strFieldName, strDispName) { } public override string DefaultValue { get { return "Roy"; } } public override BaseFieldControl FieldRenderingControl { get { BaseFieldControl fc = new RoyText(); fc.FieldName = this.InternalName; return fc; } } public override string GetValidatedString(object value) { if (!value.ToString().ToUpper().StartsWith("Roy")) { throw new SPFieldValidationException("内容必须以Roy开头!"); } return value.ToString(); } } public class RoyText : BaseFieldControl { protected TextBox txtRoy; protected override void CreateChildControls() { base.CreateChildControls(); this.TemplateContainer.FindControl("txtRoy"); txtRoy = new TextBox(); this.Controls.Add(txtRoy); } public override object Value { get { this.EnsureChildControls(); return txtRoy.Text; } set { this.EnsureChildControls(); txtRoy.Text=(string)this.ItemFieldValue; } } protected override string DefaultTemplateName { get { return "RoyTextRenderingTemplate"; } } }}
3.定义XML
RoyCustomField Text RoyCustomField RoyCustomField TRUE RoyCustomField.RoyCustomField,$SharePoint.Project.AssemblyFullName$
4.打包,部署,效果图如下: