使用VS2010开发一个简单的自定义字段类型

 

  在SharePoint中创建自定义字段类型,必须完成两个工作:创建继承于SPField的字段类;编写字段的配置文件,声明字段的基本属性、字段的实现类和字段的呈现逻辑等。

  首先在SharePoint站点创建一个自定义列表,我命名为“客户资料”。

  接下来打开VS2010,并创建一个空白SharePoint项目,我的项目命名为“MyCustomFieldsDemo”,一定要选择”部署为场解决方案“,否则不能部署;

  然后添加一个类CustomAgeField.cs, 代码如下

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;

namespace MyCustomFieldsDemo
{
public class CustomAgeField : SPFieldText
{
//必须声明如下两个构造函数并显示调用父类相应方法
public CustomAgeField(SPFieldCollection fields, string fName)
: base(fields, fName) { }
public CustomAgeField(SPFieldCollection fields, string typeName, string displayName)
: base(fields, typeName, displayName) { }

///<summary>
/// 字段的默认值
///</summary>
public override string DefaultValue
{
get
{
return "18";
}
}

///<summary>
/// 判断该字段输入的年龄是否合法
///</summary>
///<param name="value"></param>
///<returns></returns>
public override string GetValidatedString(object value)
{
if (value == null)
{
throw new SPFieldValidationException("*不能为空值");
}

string valueStr = value.ToString();
int i = 0;
if (!int.TryParse(valueStr, out i) || i < 0 || i > 150)
{
throw new SPFieldValidationException("*年龄输入不合法");
}

return valueStr;
}
}
}

 

  紧接着创建相应XML配置文档,先添加名为”XML”的SharePoint映射文件夹如下图所示:

然后在该映射文件夹下添加一个XML文档,我命名为“fldtypesAgeCustomFields.xml”,这里注意这个XML文档的名称一定是“fieldtypes*.xml”的形式。XML文档的代码如下:

View Code
<?xml version="1.0" encoding="utf-8" ?>
<FieldTypes>
<FieldType>
<Field Name="TypeName">CustomAgeField</Field>
<Field Name="ParentType">Text</Field>
<Field Name="TypeDisplayName">年龄</Field>
<Field Name="TypeShortDescription">客户年龄</Field>
<Field Name="UserCreatable">TRUE</Field>
<Field Name="FieldTypeClass">
MyCustomFieldsDemo.CustomAgeField,
$SharePoint.Project.AssemblyFullName$
</Field>
</FieldType>
</FieldTypes>

关于该XML文档的各节点说明如下表所示:

属性或节点

说明

TypeName

字段类型的唯一名称,不能重复

TypeDisplayName

字段显示名

InternalType

字段内部名称

FieldTypeClass

字段的实现类,需要采用类的全称(含dll名称)

SQLType

字段的存储类型

ParentType

字段的父类名称

Sortable

是否允许排序

FieldEditorUserControl

字段的属性编辑控件

Filterable

是否允许过滤

HeaderPattern

基于字段的栏显示在列表上时标题行呈现定义

DisplayPattern

基于字段的栏在显示页面(DispForm)时的呈现定义

EditPattern

基于字段的栏在编辑页面(EditForm)时的呈现定义

NewPattern

基于字段的栏在新建页面(NewForm)时的呈现定义

OK,现在可以部署了,部署成功后在SharePoint站点的“客户资料”列表下点击“列表工具”选项卡下的“列表“选项卡,再点击”创建栏“,如下图所示

其他选项保持默认值,单击”确定“按钮,这时”客户资料“列表就多了”客户年龄“一栏,我们再点击添加新项目,这个时候大家可以发现除了标题还多一个字段”客户年龄“,如果我们在该字段输入不合法,比如”-56“就提示错误,这个错误就是我们在CustomAgeField类里所声明抛出的异常。

OK,完工!



posted @ 2011-11-16 01:03  dong.net  阅读(1834)  评论(0编辑  收藏  举报