Mar. 22nd, 2007
Snaplines on Custom Controls
Mar. 22nd, 2007 05:54 pmNote - originally written for our internal .Net discussion forum. I wanted to archive it somewhere public so that I could find it again later. Because frankly the MS documentation sucks ass.
====
You may have noticed that when you create a custom usercontrol it doesn't come with a "text" snapline. Which makes it very hard to align labels, etc. to it using the IDE.
There is a simple way to do so, but if it's documented anywhere by MS then I'm darned if I could find it. I did eventually track down a way of doing so, which worked for me without any problems.
If you create a usercontrol called "MyUserControl", then you need to go into its code and add a designer attribute above the class declaration like so:
You'll then need to create a SnaplineControlDesigner that looks like this:
Which, as you can see, uses its pointer to the original control to get the control's height and then place the snapline 4 pixels up. Obviously, if you want it to be 5,7 or 23 pixels up, then you can simply change that.
====
You may have noticed that when you create a custom usercontrol it doesn't come with a "text" snapline. Which makes it very hard to align labels, etc. to it using the IDE.
There is a simple way to do so, but if it's documented anywhere by MS then I'm darned if I could find it. I did eventually track down a way of doing so, which worked for me without any problems.
If you create a usercontrol called "MyUserControl", then you need to go into its code and add a designer attribute above the class declaration like so:
[Designer(typeof(SnaplineControlDesigner))] public partial class MyUserControl1 : UserControl { public MyUserControl1() { InitializeComponent(); } }
You'll then need to create a SnaplineControlDesigner that looks like this:
public class SnaplineControlDesigner : ControlDesigner { public override IList SnapLines { get { Control control = this.Component as Control; ArrayList snapLines = base.SnapLines as ArrayList; snapLines.Add( new SnapLine(SnapLineType.Baseline, control.Height - 4, SnapLinePriority.Medium)); return snapLines; } } }
Which, as you can see, uses its pointer to the original control to get the control's height and then place the snapline 4 pixels up. Obviously, if you want it to be 5,7 or 23 pixels up, then you can simply change that.