Baseline snaplines in custom Winforms controls

后端 未结 5 1629
余生分开走
余生分开走 2020-12-08 07:19

I have a custom user control with a textbox on it and I\'d like to expose the baseline (of the text in the textbox) snapline outside of the custom control. I know that you

5条回答
  •  半阙折子戏
    2020-12-08 07:26

    Thanks to all those for the help. This was a tough one to swallow. The thought having a private sub-class in every UserControl wasn't very palatable.

    I came up with this base class to help out..

    [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;
                }
            }
        }
    }
    

    Next, derive your UserControl from this base:

    public partial class MyControl : UserControlBase
    {
        protected override Control SnapLineControl
        {
            get
            {
                return txtTextBox;
            }
        }
    
        ...
    
    }
    

    Thanks again for posting this.

提交回复
热议问题