- はじめに
- C#のカスタムコントロールに対して独自のプロパティを保持できるようにしたい
- 独自のプロパティはプロパティが展開するような作りにしたい
- (例) サイズ内に幅、高さのプロパティを保持する
2. 動作イメージ
- デザインのプロパティウィンドウでカスタムコントロール毎にプロパティを保持できるにする
3. 独自プロパティ用クラスの作成
- クラスの先頭に
[TypeConverter(typeof(ExpandableObjectConverter))]
の属性を追加する - プライベートな独自プロパティに対してパブリックなGet,Setメソッドを準備する
- ToStringメソッドの結果がプロパティ全体の表示に使用される
[TypeConverter(typeof(ExpandableObjectConverter))]
public class MyProperty
{
private int left; // 独自プロパティ1
private int top; // 独自プロパティ2
private int right; // 独自プロパティ3
private int bottom; // 独自プロパティ4
public MyProperty(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public int Left
{
get
{
return left;
}
set
{
left = value;
}
}
public int Top
{
get
{
return top;
}
set
{
top = value;
}
}
public int Right
{
get
{
return right;
}
set
{
right = value;
}
}
public int Bottom
{
get
{
return bottom;
}
set
{
bottom = value;
}
}
public override string ToString()
{
return String.Format("{0}, {1}, {2}, {3}",
this.Left, this.Top, this.Right, this.Bottom);
}
}
4. 独自プロパティを持つ カスタムコントロールの作成
- Labelクラスを継承してカスタムコントロールを作成する
- 独自プロパティ用クラスをプロパティに追加する
- 3行目に初期値を設定しているが、この行がないとGUIでプロパティが表示されないため注意する
public partial class LabelEx : System.Windows.Forms.Label
{
private MyProperty _myProperty = new MyProperty(0, 0, 0, 0);
public LabelEx()
{
InitializeComponent();
}
protected override void OnPaint(PaintEventArgs pe)
{
base.OnPaint(pe
}
public MyProperty MyProperty
{
get
{
return _myProperty;
}
set
{
_myProperty = value;
}
}
}
5. 動作確認
- カスタムコントロールに対してプロパティがセットできることを確認
6. 参考文献