ユーザーコントロールのスナップを自作する
ユーザーコントロールを作成してテキストボックスなんか置いたりすると、スナップ(ピンクの線)が消えてしまって配置するのがめんどくさくなります。
そこで、ユーザーコントロールにもスナップを追加します。
とりあえずUserControlを継承したクラスを作成します。
この後作成するスナップ付きのユーザーコントロールにこのクラスを使います。
[Designer(typeof(UserControlSnapLineDesigner))] public class UserControlBase: UserControl { protected virtual Control SnapLineControl { get { return null; } } private class UserControlSnapLineDesigner: ControlDesigner { public override IList SnapLines { get { IList snapLines = base.SnapLines; Control targetControl = ( this.Control as UserControlBase ).SnapLineControl; if( targetControl == null ) return snapLines; using( ControlDesigner controlDesigner = TypeDescriptor.CreateDesigner(targetControl, typeof(IDesigner)) as ControlDesigner ) { if( controlDesigner == null ) return snapLines; controlDesigner.Initialize(targetControl); foreach( SnapLine line in controlDesigner.SnapLines ) { if( line.SnapLineType == SnapLineType.Baseline ) { snapLines.Add(new SnapLine(SnapLineType.Baseline, line.Offset + targetControl.Top, line.Filter, line.Priority)); break; } } } return snapLines; } } } }
先ほど作ったクラスを使用してユーザーコントロールを作成します。
作成するユーザーコントロールにはテキストボックスが配置してあり、このテキストボックスのスナップを持ってきます。
UserControlBase で作成したSnapLineControlをオーバーライドでコントロールを指定します。
public partial class ユーザーコントロール: UserControlBase { // ~ 細かいところは省略します ~ //ここで指定するだけ↓ protected override Control SnapLineControl { get { return this.textBox1; } } }
これでテキストボックスのピンクの線がユーザーコントロールにもつくようになりました。
引用:.net - Baseline snaplines in custom Winforms controls - Stack Overflow