2013年3月14日 星期四

最簡單的CollectionEditor範例

Keyword: CollectionEditor、伺服器控制項、Server Control

程式碼部分如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing.Design;
using System.ComponentModel.Design;
[assembly: TagPrefix("LD.SC", "hyh")]
namespace LD.SC
{
    [Serializable]    
    public class Sample
    {
        public String Text { get; set; }
        public String Value { get; set; }
    }
    public class ExCollectionEditor : CollectionEditor
    {
        public ExCollectionEditor(Type type)
            :base(type)         
        {
            
        }
        protected override bool CanSelectMultipleInstances()
        {
            return false;
        }
        protected override Type[] CreateNewItemTypes()
        {
            Type[] ItemTypes = new Type[1]; //這邊需要給一個固定的大小
            ItemTypes[0] = typeof(Sample); //單一元素的型別
            return ItemTypes;
        }
    }
    [ToolboxData("<{0}:KVP runat=server></{0}:KVP>")]
    public class KVP : WebControl
    {
        List<Sample> _SampleList = null;
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [PersistenceMode(PersistenceMode.InnerProperty)]        
        [Editor(typeof(ExCollectionEditor), typeof(UITypeEditor))]
        public List<Sample> KeyValuePairs
        {
            get
            {
                if (_SampleList == null)
                {
                    _SampleList = new List<Sample>();
                }
                return _SampleList;
            }
        }
        protected override void RenderContents(HtmlTextWriter output)
        {
            output.Write("SAMPLE");
        }
    }    
}

收工,回家。不是啦,順便看一下使用的畫面唄。


image


原始檔顯示如下:

<hyh:KVP ID="KVP1" runat="server">
    <KeyValuePairs>
        <hyh:Sample Text="AA" Value="1" />
        <hyh:Sample Text="BB" Value="2" />
    </KeyValuePairs>
</hyh:KVP>


 


參考資料:


沒有留言:

張貼留言