SharePoint 2010 自定义字段开发

http://www.cnblogs.com/flowman/archive/2012/10/31/2748049.html

代码没有来得及优化,仅供参考。我只是参考了部分代码。

 

SharePoint 2010自带字段类型有很多,如单行文本,日期时间,下拉列表,数字等等。但往往这些不能满足我们的需要,比如要求一个大写金额的字段,用户输入数字,要求显示成大写,这时候就不能满足需求了。那么我们就要使用自定义开发的字段类型了。下面以开发大写金额字段来说明SharePoint 2010自定义字段开发。
    SharePoint 2010创建栏时默认的字段类型如下:

SharePoint 2010 自定义字段开发_第1张图片

   开发自定义的大写金额类型后,也会在这里出现,如下图

先看一下效果吧,首先创建一个数字字段,即是用户输入数字的字段,点击确定。


然后再创建一个我们开发的大写金额字段

SharePoint 2010 自定义字段开发_第2张图片

创建完这两个字段后,在列表上点击添加新项目

SharePoint 2010 自定义字段开发_第3张图片

当在小写文本框内输入数字,大写金额会自动跟着显示出来,如下图

SharePoint 2010 自定义字段开发_第4张图片

看到效果后,下面介绍大写金额字段下实现过程。

1、先了解MOSS内部的字段类型,如下表,大写金额字段继承 SPFieldMultiColumn这字段类型开发

SPFieldText

 单行文本

 这个可能是用的最为广泛的字段类型了,它的输入界面就是一个单行文本框,没有数据验证功能(除了是否为空)。可以设置最大长度(局限在255以内)。

 SPFieldMultiLineText

 多行文本

 输入界面是一个textarea,根据设置不同,可以是纯文本或者是带格式文本的(按照html格式保存的)。

 SPFieldNumber

 数字

 输入界面是textbox,但是带有数据验证(是否为数字,以及最大/最小值等)。

 SPFieldCurrency

 货币

 和数字其实差不多,只不过现实的时候会多一个货币符号。

 SPFieldBoolean

 是/否

 一个CheckBox

 SPFieldDateTime

 日期

 一个带picker的textbox,可以选择“日期和时间”或“仅日期”

 SPFieldChoice

 选项(单选)

 可以以dropdownlist或者radio button的形式出现。这个字段有点点特别,虽然它看上去只能存一个值,但其实它是多选类(SPFieldMultiChoice)的子类

 SPFieldMultiChoice

 选项(多选)

 如果使用多选,那么是通过一组checkbox输入的。在这个类里面定义了这个字段中究竟有哪些选项(通过Choices属性,自然,作为它子类的SPFieldChoice也有这个属性)。于之相对应的,可以通过SPFieldMultiChoiceValue类来访问它的值。

 SPFieldRatingScale

 评估范围

刚才介绍过了,它其实也是多选类(SPFieldMultiChoice)的子类。于之对应的值类型为SPFieldRatingScaleValue

 SPFieldUrl

 链接或图片

 可以是链接,也可以是图片,它包含url和描述信息两个部分,通过其值类型SPFieldUrlValue可以很方便的得到这两部分。

 SPFieldLookup

 查阅项

 通过dropdownlist完成单选,一个特殊的listbox完成多选(wss3.0支持查阅项多选了!),由于每个被查阅的项会有id和文本,所以也需要有值类型,这个比较特殊,有两种值类型,SPFieldLookupValue和SPFieldLookupValueCollection(因为支持多选了嘛)。然后在SPFieldLookup类中,定义了要查阅哪个列表的哪个字段,以及是哪个网站上的列表。是的!wss3.0中的查阅项其实是支持跨网站查阅的(通过设定LookupWebId属性),但是在默认的界面上并没有暴露出一点。所以一个跨网站查阅项是一个很值得一做的自定义字段类型!

 SPFieldUser

 用户和用户组

 它的输入是通过一个带有AJAX支持的输入框完成的,这是一个很强大的控件。其实这个类是SPFieldLookup的子类,因为它们做的事情在本质上都差不多。相应的,其值类型SPFieldUserValue也是SPFieldLookupValue的子类,还有SPFieldUserValueCollection……

 SPFieldMultiColumn

 多栏

 这是另一个很特殊的字段类型,默认情况下我们无法直接使用它,使用它的唯一途径就是通过自定义字段类型继承它来完成我们的需求。顾名思义,这是一个能在一个字段中储存多个信息的字段类型。

大写金额字段项目目录情况

SharePoint 2010 自定义字段开发_第5张图片

SPLegalAmountField.cs代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Xml;
using System.Reflection;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using System.Collections.Specialized;
namespace FlowMan.WebControls.SPLegalAmountField
{
    [CLSCompliant(false)]
    public class SPLegalAmountField : SPFieldMultiColumn
    {
        //创建字段保存创建配置属性:关联的小写字段
        const string SPLegalAmountField_RELEVANCELISTFIELD = "SPLegalAmountFieldRelevanceListField";
        //创建字段保存创建配置属性:呈现出来的大小金额文本框长度
        const string SPLegalAmountField_TEXTBOXWIDTH = "SPLegalAmountFieldTextboxWidth";
       
        public SPLegalAmountField(SPFieldCollection fields, string fieldname)
            : base(fields, fieldname)
        {
            _splegalAmountFieldRelevanceListField = "" + base.GetCustomProperty(SPLegalAmountField_RELEVANCELISTFIELD);
            _splegalAmountFieldTextboxWidth = "" + base.GetCustomProperty(SPLegalAmountField_TEXTBOXWIDTH);
          
        }
        public SPLegalAmountField(SPFieldCollection fields, string typeName, string displaydname)
            : base(fields, typeName, displaydname)
        {
            _splegalAmountFieldRelevanceListField = "" + base.GetCustomProperty(SPLegalAmountField_RELEVANCELISTFIELD);
            _splegalAmountFieldTextboxWidth = "" + base.GetCustomProperty(SPLegalAmountField_TEXTBOXWIDTH);

        }
        public override object GetFieldValue(string value)
        {
            if (string.IsNullOrEmpty(value))
                return null;
            return new SPLegalAmountFieldValue(value);

        }


        private string _splegalAmountFieldRelevanceListField;
        private string _splegalAmountFieldTextboxWidth;

        public string SPLegalAmountFieldRelevanceListField
        {
            get
            {
                return _splegalAmountFieldRelevanceListField;
            }
            set
            {
                _splegalAmountFieldRelevanceListField = value;
                this.SetCustomPropertytoCache(SPLegalAmountField_RELEVANCELISTFIELD, value);
            }
        }
        public string SPLegalAmountFieldTextboxWidth
        {
            get
            {
                return _splegalAmountFieldTextboxWidth;
            }
            set
            {
                _splegalAmountFieldTextboxWidth = value;
                this.SetCustomPropertytoCache(SPLegalAmountField_TEXTBOXWIDTH, value);
            }
        }

        private static readonly Dictionary<string, StringDictionary>
            CustomPropertiesCache = new Dictionary<string, StringDictionary>();
        private string ContextKey
        {
            get
            {
                return this.ParentList.ID.ToString() + "_" + System.Web.HttpContext.Current.GetHashCode();
            }
        }
        protected void SetCustomPropertytoCache(string key, string value)
        {
            StringDictionary plist = null;
            if (CustomPropertiesCache.ContainsKey(ContextKey))
            {
                plist = CustomPropertiesCache[ContextKey];
            }
            else
            {
                plist = new StringDictionary();
                CustomPropertiesCache.Add(ContextKey, plist);
            }
            if (plist.ContainsKey(key))
            {
                plist[key] = value;
            }
            else
            {
                plist.Add(key, value);
            }
        }
        protected string GetCustomPropertyFromCache(string key)
        {
            if (CustomPropertiesCache.ContainsKey(ContextKey))
            {
                StringDictionary plist = CustomPropertiesCache[ContextKey];
                if (plist.ContainsKey(key))
                    return plist[key];
                else
                    return "";
            }
            else
            {
                return "";
            }
        }
        public override void OnAdded(SPAddFieldOptions op)
        {
            base.OnAdded(op);
            Update();
        }
        public override void Update()
        {

            base.SetCustomProperty(SPLegalAmountField_RELEVANCELISTFIELD, this.GetCustomPropertyFromCache(SPLegalAmountField_RELEVANCELISTFIELD));
            base.SetCustomProperty(SPLegalAmountField_TEXTBOXWIDTH, this.GetCustomPropertyFromCache(SPLegalAmountField_TEXTBOXWIDTH));

            base.Update();
        }


        public override BaseFieldControl FieldRenderingControl
        {
            [SharePointPermission(SecurityAction.LinkDemand, ObjectModel = true)]

            get
            {
                BaseFieldControl _renderingControl = new SPLegalAmountFieldControl();

                _renderingControl.FieldName = InternalName;
                return _renderingControl;

            }
        }
        /// <summary>
        /// 提交表单时候的验证数据类型
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override string GetValidatedString(object value)
        {
            string strValue = "" + value;
            if (Required && strValue == "")
            {
                throw new SPFieldValidationException(System.Web.HttpContext.GetGlobalResourceObject("FlowMan.WebControls", "SPLegalAmountField_Required").ToString());
            }

            return base.GetValidatedString(value);
        }

    }
}

SPLegalAmountFieldValue.cs类代码
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Xml;
using System.Reflection;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Security;
using System.Security.Permissions;

namespace FlowMan.WebControls.SPLegalAmountField
{
    public class SPLegalAmountFieldValue : SPFieldMultiColumnValue
    {
        private const int numberOfFields = 2;
        public SPLegalAmountFieldValue() : base(numberOfFields) { }
        public SPLegalAmountFieldValue(string value) : base(value) { }
        public string AmountCapital
        {
            get { if (this != null && this.Count > 0) return this[0]; else return ""; }
            set { if (value != null) this[0] = value; else this[0] = ""; }
        }
        public string AmountNumber
        {
            get { if (this != null && this.Count > 1) return this[1]; else return ""; }
            set { if (value != null) this[1] = value; else this[1] = ""; }
        }

    }
}


 

 

SPLegalAmountFieldEditor.ascx 代码

复制代码
<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %><%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><%@ Register TagPrefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><%@ Register TagPrefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><%@ Register TagPrefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %><%@ Import Namespace="Microsoft.SharePoint" %><%@ Register TagPrefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages"    Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SPLegalAmountFieldEditor.ascx.cs"    Inherits="FlowMan.WebControls.SPLegalAmountField.SPLegalAmountFieldEditor" %><table cellpadding="0" cellspacing="0" border="0">    <tr>        <td>            <b>                <asp:Literal runat="server" ID="Literal2" Text="<%$Resources:FlowMan.WebControls,SPLegalAmountField_EditorField%>"></asp:Literal>:</b>        </td>        <td>                     <asp:DropDownList ID="DrRelevanceListField" runat="server">            </asp:DropDownList>        </td>    </tr>    <tr>        <td>            <b>                 <asp:Literal ID="Literal1" runat="server" Text="<%$Resources:FlowMan.WebControls,SPLegalAmountField_EditorFieldTextboxWidth%>"></asp:Literal>:</b>        </td>        <td>                     <asp:TextBox ID="txtTextboxWidth" runat="server"></asp:TextBox>        </td>    </tr></table>
复制代码

SPLegalAmountFieldEditor.cs代码

复制代码
using System;using System.Web.UI;using System.Web.UI.WebControls;using Microsoft.SharePoint.WebControls;using Microsoft.SharePoint;using System.Web;using System.Collections.Generic;using System.Text;using System.Collections.Specialized;using Microsoft.SharePoint.Utilities;namespace FlowMan.WebControls.SPLegalAmountField{    using Microsoft.SharePoint;    using Microsoft.SharePoint.WebControls;    using System.Web.UI.HtmlControls;    public class SPLegalAmountFieldEditor : UserControl, IFieldEditor    {        //定义编辑字段的两个控件        protected DropDownList DrRelevanceListField = null;        protected TextBox txtTextboxWidth = null;        bool IFieldEditor.DisplayAsNewSection        {            get { return false; }        }        //编辑字段配置信息绑定到控件上        void IFieldEditor.InitializeWithField(SPField field)        {            if (!Page.IsPostBack)            {                this.EnsureChildControls();                BindSPListFieldData(SPContext.Current.ListId, DrRelevanceListField);            }            if (!Page.IsPostBack&&field != null)            {                SPLegalAmountField fields = (SPLegalAmountField)field;                this.DrRelevanceListField.SelectedValue = fields.SPLegalAmountFieldRelevanceListField;                this.txtTextboxWidth.Text = fields.SPLegalAmountFieldTextboxWidth;            }        }        //绑定当前列表的数字字段到下拉控件        void BindSPListFieldData(Guid listid,DropDownList drlist)        {            using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))            {                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))                {                    drlist.Items.Clear();                    SPList splist = web.Lists[listid];                    SPFieldCollection splistfield = splist.Fields;                    foreach (SPField spfsitem in splistfield)                    {                        if (spfsitem.Reorderable)                        {                            if (spfsitem.Type == SPFieldType.Number || spfsitem.Type == SPFieldType.Currency)                            {                                string _text = spfsitem.Title;                                string _value = spfsitem.InternalName;                                System.Web.UI.WebControls.ListItem litem = new System.Web.UI.WebControls.ListItem(_text, _value);                                drlist.Items.Add(litem);                            }                        }                    }                }            }        }               //保存配置的值        void IFieldEditor.OnSaveChange(SPField field, bool isNewField)        {            this.EnsureChildControls();            if (field != null)            {                SPLegalAmountField CuserField = (SPLegalAmountField)field;                CuserField.SPLegalAmountFieldRelevanceListField = DrRelevanceListField.SelectedValue;                CuserField.SPLegalAmountFieldTextboxWidth = txtTextboxWidth.Text;            }        }    }}
复制代码

SPLegalAmountFieldControl.ascx 代码

复制代码
<%@ Control Language="C#" Debug="true" %><%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %><%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> <SharePoint:RenderingTemplate ID="SPLegalAmountFieldControl" runat="server">    <Template>   <span id="spSPLegalAmountFieldControl" >           <asp:TextBox ID="txtSPLegalAmountField" class="txtSPLegalAmountField" onfocus="this.blur()"  runat="server" ></asp:TextBox>              <asp:HiddenField ID="hidSPLegalAmountField" Value="" runat="server" />                 <asp:HiddenField ID="hidSPLegalAmountFieldPropery" Value="" runat="server" />             </span>      <script type="text/javascript">                  function convert(str, inputmoneycontrol) {             // if (str != "") {                  value = AmountInWords(str,4); //调用自定义函数转换                  return value;             // }             // else return "零元整";          }                   function AmountInWords(dValue, maxDec) {              // 验证输入金额数值或数值字符串:                 dValue = dValue.toString().replace(/,/g, "");              dValue = dValue.replace(/^0+/, ""); // 金额数值转字符、移除逗号、移除前导零                 if (dValue == "") { return "零元整"; } // (错误:金额为空!)                 else if (isNaN(dValue)) { return '<asp:Literal ID="Literal2" Text="<%$Resources:FlowMan.WebControls,SPLegalAmountField_AlertInputLawful%>" runat="server"></asp:Literal>'; }              var minus = ""; // 负数的符号“-”的大写:“负”字。可自定义字符,如“(负)”。                 var CN_SYMBOL = ""; // 币种名称(如“人民币”,默认空)                 if (dValue.length > 1) {                  if (dValue.indexOf('-') == 0) { dValue = dValue.replace("-", ""); minus = ""; } // 处理负数符号“-”                     if (dValue.indexOf('+') == 0) { dValue = dValue.replace("+", ""); } // 处理前导正数符号“+”(无实际意义)                 }              var vInt = "", vDec = ""; // 字符串:金额的整数部分、小数部分                 var resAIW; // 字符串:要输出的结果                 var parts; // 数组(整数部分.小数部分),length=1时则仅为整数。                 var digits, radices, bigRadices, decimals; //数组:数字(0~9——零~玖);基(十进制记数系统中每个数字位的基是10——拾,佰,仟);大基(万,亿,兆,京,垓,杼,穰,沟,涧,正);辅币(元以下,角/分/厘/毫/丝)。                 var zeroCount; // 零计数                 var i, p, d; // 循环因子;前一位数字;当前位数字。                 var quotient, modulus; // 整数部分计算用:商数、模数。                 // 金额数值转换为字符,分割整数部分和小数部分:整数、小数分开来搞(小数部分有可能四舍五入后对整数部分有进位)。                 var NoneDecLen = (typeof (maxDec) == "undefined" || maxDec == null || Number(maxDec) < 0 || Number(maxDec) > 5); // 是否未指定有效小数位(true/false)                 parts = dValue.split('.'); // 数组赋值:(整数部分.小数部分),Array的length=1则仅为整数。                 if (parts.length > 1) {                  vInt = parts[0];                  vDec = parts[1]; // 变量赋值:金额的整数部分、小数部分                     if (NoneDecLen) {                      maxDec = vDec.length > 5 ? 5 : vDec.length;                  }                  // 未指定有效小数位参数值时,自动取实际小数位长但不超5。                     var rDec = Number("0." + vDec);                  rDec *= Math.pow(10, maxDec);                  rDec = Math.round(Math.abs(rDec));                  rDec /= Math.pow(10, maxDec); // 小数四舍五入                     var aIntDec = rDec.toString().split('.');                  if (Number(aIntDec[0]) == 1) {                      vInt = (Number(vInt) + 1).toString();                  } // 小数部分四舍五入后有可能向整数部分的个位进位(值1)                     if (aIntDec.length > 1) {                      vDec = aIntDec[1];                  } else { vDec = ""; }              } else {                  vInt = dValue; vDec = ""; if (NoneDecLen) { maxDec = 0; }              }              if (vInt.length > 44) { return '<asp:Literal ID="Literal3" Text="<%$Resources:FlowMan.WebControls,SPLegalAmountField_AlertInputLawful%>" runat="server"></asp:Literal>'; }              // 准备各字符数组 Prepare the characters corresponding to the digits:                 digits = new Array("", "", "", "", "", "", "", "", "", ""); // 零~玖                 radices = new Array("", "", "", ""); // 拾,佰,仟                 bigRadices = new Array("", "", "亿", "", "", "", "", "", "", "", ""); // 万,亿,兆,京,垓,杼,穰,沟,涧,正                 decimals = new Array("", "", "", "", ""); // 角/分/厘/毫/丝                 resAIW = ""; // 开始处理                 // 处理整数部分(如果有)                 if (Number(vInt) > 0) {                  zeroCount = 0;                  for (i = 0; i < vInt.length; i++) {                      p = vInt.length - i - 1; d = vInt.substr(i, 1); quotient = p / 4; modulus = p % 4;                      if (d == "0") {                          zeroCount++;                      } else {                          if (zeroCount > 0) { resAIW += digits[0]; }                          zeroCount = 0; resAIW += digits[Number(d)] + radices[modulus];                      }                      if (modulus == 0 && zeroCount < 4) { resAIW += bigRadices[quotient]; }                  }                  resAIW += "";              }              // 处理小数部分(如果有)                 for (i = 0; i < vDec.length; i++) { d = vDec.substr(i, 1); if (d != "0") { resAIW += digits[Number(d)] + decimals[i]; } }              // 处理结果                 if (resAIW == "") { resAIW = "" + ""; } // 零元                 if (vDec == "") { resAIW += ""; } // ...元整                 resAIW = CN_SYMBOL + minus + resAIW; // 人民币/负......元角分/整                 return resAIW;          }         </script>    </Template></SharePoint:RenderingTemplate><SharePoint:RenderingTemplate ID="SPLegalAmountFieldControlDisplay" runat="server">    <Template>         <asp:Label ID="LabSPLegalAmountField" class="LabSPLegalAmountField" runat="server"></asp:Label>        <asp:HiddenField ID="LabhidSPLegalAmountField" Value="" runat="server" />       </Template></SharePoint:RenderingTemplate>
复制代码

SPLegalAmountFieldControl.cs代码

复制代码
using System;using System.Data;using System.Runtime.InteropServices;using System.Web.UI.WebControls;using Microsoft.SharePoint;using Microsoft.SharePoint.WebControls;using System.Web.UI;using System.Text;namespace FlowMan.WebControls.SPLegalAmountField{    [CLSCompliant(false)]    public class SPLegalAmountFieldControl : BaseFieldControl    {        //定义表单呈现状态时的控件        protected TextBox txtSPLegalAmountField;        protected HiddenField hidSPLegalAmountField;        protected HiddenField hidSPLegalAmountFieldPropery;        protected Label LabSPLegalAmountField;        protected HiddenField LabhidSPLegalAmountField;                     protected override string DefaultTemplateName        {            get            {                //下面的用户控件名,<SharePoint:RenderingTemplate> 控件的ID 需要等于这个值                 return "SPLegalAmountFieldControl";            }        }        public override string DisplayTemplateName        {            get            {                return "SPLegalAmountFieldControlDisplay";            }        }        //取值与赋值        public override object Value        {            get            {                EnsureChildControls();                SPLegalAmountFieldValue fieldValue = new SPLegalAmountFieldValue();                SPLegalAmountField field = (SPLegalAmountField)base.Field;                FormField txtAmountLower = GetCurrentFormFieldControl((Control)this.Page, field.SPLegalAmountFieldRelevanceListField);                if (txtAmountLower == null || txtAmountLower.Value == null)                {                    if (SPContext.Current.Item[field.SPLegalAmountFieldRelevanceListField] != null)                    {                        SPFieldType filetype = SPContext.Current.Item.Fields.GetFieldByInternalName(field.SPLegalAmountFieldRelevanceListField).Type;                        SPFieldCalculated filecal = (SPFieldCalculated)SPContext.Current.Item.Fields.GetFieldByInternalName(field.SPLegalAmountFieldRelevanceListField);                        string fieldCalculatedValue = filecal.GetFieldValueAsText(SPContext.Current.Item[field.SPLegalAmountFieldRelevanceListField]);                        double amount = Convert.ToDouble(fieldCalculatedValue);                        fieldValue.AmountCapital = new RMBCapitalization().RMBAmount(amount);                        fieldValue.AmountNumber = fieldCalculatedValue;                    }                    else                    {                        fieldValue.AmountCapital = txtSPLegalAmountField.Text;                        fieldValue.AmountNumber = hidSPLegalAmountField.Value;                    }                }                else                {                    fieldValue.AmountCapital = txtSPLegalAmountField.Text;                    fieldValue.AmountNumber = hidSPLegalAmountField.Value;                }                                     return fieldValue;            }            set            {                EnsureChildControls();                SPLegalAmountFieldValue fieldValue = (SPLegalAmountFieldValue)value;                if (LabSPLegalAmountField != null && fieldValue!=null)                {                    LabSPLegalAmountField.Text = fieldValue.AmountCapital;                    LabhidSPLegalAmountField.Value = fieldValue.AmountNumber;                }                else if (txtSPLegalAmountField != null && fieldValue != null)                {                    txtSPLegalAmountField.Text = fieldValue.AmountCapital;                    hidSPLegalAmountField.Value = fieldValue.AmountNumber;                    SPLegalAmountField field = (SPLegalAmountField)Field;                    hidSPLegalAmountFieldPropery.Value = field.SPLegalAmountFieldRelevanceListField;                }                base.Value = fieldValue;            }        }        public override void Focus()        {            EnsureChildControls();            // txtCurrentUserDepart.Focus();        }               protected override void CreateChildControls()        {            if (Field == null) return;            if (this.ControlMode == SPControlMode.Display)            {                this.TemplateName = this.DisplayTemplateName;            }            base.CreateChildControls();            if (ControlMode == SPControlMode.Display)            {                LabSPLegalAmountField = (Label)TemplateContainer.FindControl("LabSPLegalAmountField");                if (LabSPLegalAmountField == null)                    throw new ArgumentException("未找到LabSPLegalAmountField控件");                LabhidSPLegalAmountField = (HiddenField)TemplateContainer.FindControl("LabhidSPLegalAmountField");                if (LabhidSPLegalAmountField == null)                    throw new ArgumentException("未找到LabhidSPLegalAmountField控件");                SPLegalAmountFieldValue fieldValue = (SPLegalAmountFieldValue)this.ItemFieldValue;                if (fieldValue != null)                {                    LabSPLegalAmountField.Text = fieldValue.AmountCapital;                    LabhidSPLegalAmountField.Value = fieldValue.AmountNumber;                }            }            else            {                txtSPLegalAmountField = (TextBox)TemplateContainer.FindControl("txtSPLegalAmountField");                hidSPLegalAmountField = (HiddenField)TemplateContainer.FindControl("hidSPLegalAmountField");                hidSPLegalAmountFieldPropery = (HiddenField)TemplateContainer.FindControl("hidSPLegalAmountFieldPropery");                if (txtSPLegalAmountField == null)                    throw new ArgumentException("未找到txtSPLegalAmountField控件");                if (hidSPLegalAmountField == null)                    throw new ArgumentException("未找到hidSPLegalAmountField控件");                if (hidSPLegalAmountFieldPropery == null)                    throw new ArgumentException("未找到hidSPLegalAmountFieldPropery控件");                SPLegalAmountField field = (SPLegalAmountField)base.Field;                if (!string.IsNullOrEmpty(field.SPLegalAmountFieldTextboxWidth))                    txtSPLegalAmountField.Width = Convert.ToInt32(field.SPLegalAmountFieldTextboxWidth.Trim());                              FormField txtAmountLower = GetCurrentFormFieldControl((Control)this.Page, field.SPLegalAmountFieldRelevanceListField);                if (txtAmountLower != null)                {                    string _txtAmountLowerId = txtAmountLower.Controls[0].ClientID + txtAmountLower.Controls[0].ClientID.Replace(txtAmountLower.ClientID, "") + "_TextField";                     StringBuilder jsstr = new StringBuilder();                    jsstr.AppendLine("<script type=\"text/javascript\">");                    jsstr.AppendLine("function convertAmount"+_txtAmountLowerId+"(){");                    jsstr.AppendLine("var _this=document.getElementById('" + _txtAmountLowerId + "');");                    jsstr.AppendLine("var _amountlegal = convert(_this.value,_this);");                    jsstr.AppendLine("document.getElementById('" + txtSPLegalAmountField.ClientID + "').value = _amountlegal;");                    jsstr.AppendLine("document.getElementById('" + hidSPLegalAmountField.ClientID + "').value = _this.value;");                    jsstr.AppendLine("}");                    jsstr.AppendLine("if(/msie/i.test(navigator.userAgent)){");                    jsstr.AppendLine("document.getElementById('" + _txtAmountLowerId + "').onpropertychange = convertAmount"+_txtAmountLowerId+"");                    jsstr.AppendLine("}");                    jsstr.AppendLine("else");                    jsstr.AppendLine("{");                    jsstr.AppendLine("document.getElementById('" + _txtAmountLowerId + "').addEventListener(\"input\",convertAmount" + _txtAmountLowerId + ",false);");                    jsstr.AppendLine("}");                    jsstr.AppendLine("convertAmount" + _txtAmountLowerId + "();");                    jsstr.AppendLine("</script>");                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Amountchangejs" + field.SPLegalAmountFieldRelevanceListField, jsstr.ToString());                }            }        }              public FormField GetCurrentFormFieldControl(Control control,string fieldName)        {            FormField result = null;            if (control is FormField)            {                if (((FormField)control).Field.InternalName == fieldName)                {                    result = (FormField)control;                }            }            else            {                foreach (Control c in control.Controls)                {                    result = GetCurrentFormFieldControl(c, fieldName);                    if (result != null)                    {                        break;                    }                }            }            return result;        }    }}
复制代码

FLDTYPES_SPLegalAmountField.xml  配置代码

复制代码
<?xml version="1.0" encoding="utf-8"?><FieldTypes>  <FieldType>    <Field Name="TypeName">SPLegalAmountField</Field>    <Field Name="TypeDisplayName">$Resources:FlowMan.WebControls,SPLegalAmountField_TypeDisplayName;</Field>    <Field Name="TypeShortDescription">$Resources:FlowMan.WebControls,SPLegalAmountField_TypeShortDescription;</Field>    <Field Name="ParentType">MultiColumn</Field>    <Field Name="FieldTypeClass">FlowMan.WebControls.SPLegalAmountField.SPLegalAmountField, FlowMan.WebControls, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=9d3cecd1bba4cc9e</Field>    <Field Name="FieldEditorUserControl">/_controltemplates/FlowMan.WebControls/SPLegalAmountFieldEditor.ascx</Field>    <Field Name="UserCreatable">TRUE</Field>    <Field Name="Sortable">TRUE</Field>    <Field Name="Filterable">TRUE</Field>    <Field Name="ShowOnSureyCreate">TRUE</Field>    <Field Name="ShowOnListCreate">TRUE</Field>    <Field Name="ShowOnColumnTemplateCreate">TRUE</Field>    <PropertySchema>      <Fields>        <Field Name="SPLegalAmountFieldRelevanceListField" Type="Text" Hidden="TRUE" />        <Field Name="SPLegalAmountFieldTextboxWidth" Type="Text" Hidden="TRUE" />             </Fields>    </PropertySchema>     </FieldType></FieldTypes>
复制代码

fldtypes_SPLegalAmountField.xsl 配置代码

复制代码
<xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"                 xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt"  xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal" ddwrt:oob="true">  <xsl:output method="html" indent="no"/>  <xsl:template match="FieldRef[@FieldType='SPLegalAmountField']" mode="Note_body">    <!--Set the thisNode parameter to the current node-->    <xsl:param name="thisNode" select="." />    <!--Store the current element-->    <xsl:variable name="curElement" select="current()" />    <!--Store the field value we are rendering in a variable for easier access-->    <xsl:variable name="fldVal" >      <!--We want to return the value of the field that has the same name as the current element being processed-->      <xsl:value-of select="$thisNode/@*[name()=$curElement/@Name]"  disable-output-escaping="yes"/>    </xsl:variable>    <!--Render our result field with the home score - away score construct-->    <!-- <xsl:value-of select="substring-after($fldVal, ', ')"/>-->  <xsl:value-of select="substring-before($fldVal, ', ')"  disable-output-escaping="yes" />  </xsl:template></xsl:stylesheet>
复制代码

 

你可能感兴趣的:(SharePoint 2010 自定义字段开发)