バージョンは1.1:カスタムコントロールのプロパティの型をコントロールにしたい時に必要なTypeConverterの抽象クラス

カスタムコントロールのプロパティの型をコントロールにしたい時に必要なTypeConverterの抽象クラスです。
各、コントロール毎にTypeConverterを一から作るのはめんどくさいので、抽象クラスを作っておいて、継承先で型を指定するプロパティをオーバライドする事で指定の型のTypeConverterを作成しています。


001 using System;
002 using System.Drawing;
003 using System.Reflection;
004 using System.Collections;
005 using System.ComponentModel;
006 using System.ComponentModel.Design;
007 using System.ComponentModel.Design.Serialization;
008 namespace NAL6295.Web.UI.Controls
009 {
010 /// <summary>
011 /// コントロールのリストと選択されたコントロールの文字列を相互変換するコンバータの抽象クラス
012 /// </summary>
013 public abstract class ControlConverterAbstract:System.ComponentModel.StringConverter
014 {
015
016 /// <summary>
017 /// 選択リストに追加したいコントロールの型情報
018 /// </summary>
019 protected abstract System.Type ControlType{get;}
020
021
022
023 /// <summary>
024 /// 値リストのサポートを許可する
025 /// </summary>
026 /// <param name="context"></param>
027 /// <returns></returns>
028 public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context)
029 {
030 return true;
031 }
032
033 /// <summary>
034 /// 値リストの作成
035 /// </summary>
036 /// <param name="context"></param>
037 /// <returns>デザイン画面に存在するControlTypeプロパティで指定されたコントロールのリストを取得しそのIDリストを返す</returns>
038 public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context)
039 {
040 ArrayList selectionList = new ArrayList();
041
042 foreach(System.Web.UI.Control item in GetControlList(context))
043 {
044 selectionList.Add(item.ID);
045 }
046
047 return new System.ComponentModel.TypeConverter.StandardValuesCollection(selectionList);
048 }
049
050 /// <summary>
051 /// 文字列型から指定された型への変換
052 /// 選択リストに無い文字列が指定されていたときは、String.Emptyを返す
053 /// </summary>
054 /// <param name="context"></param>
055 /// <param name="culture"></param>
056 /// <param name="value"></param>
057 /// <returns></returns>
058 public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
059 {
060 if(value is string)
061 {
062 foreach(System.Web.UI.Control item in GetControlList(context))
063 {
064 if(item.ID == (string)value)
065 {
066 return base.ConvertFrom(context, culture, value);
067 }
068 }
069 return string.Empty;
070 }
071 return base.ConvertFrom(context, culture, value);
072 }
073
074 /// <summary>
075 /// 指定された型のリストを返す
076 /// </summary>
077 /// <param name="context"></param>
078 /// <returns></returns>
079 private object[] GetControlList(ITypeDescriptorContext context)
080 {
081 IReferenceService service = (IReferenceService)context.GetService(typeof(IReferenceService));
082 return service.GetReferences(ControlType);
083 }
084
085
086 }
087
088 }
089
090

使用例


001 public sealed class TextBoxConverter:ControlConverterAbstract
002 {
003 protected override Type ControlType
004 {
005 get
006 {
007 return typeof(TextBox);
008 }
009 }
010
011 }