Baseline snaplines in custom Winforms controls

后端 未结 5 1632
余生分开走
余生分开走 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:48

    I just had a similar need, and I solved it like this:

     public override IList SnapLines
    {
        get
        {
            IList snapLines = base.SnapLines;
    
            MyControl control = Control as MyControl;
            if (control == null) { return snapLines; }
    
            IDesigner designer = TypeDescriptor.CreateDesigner(
                control.textBoxValue, typeof(IDesigner));
            if (designer == null) { return snapLines; }
            designer.Initialize(control.textBoxValue);
    
            using (designer)
            {
                ControlDesigner boxDesigner = designer as ControlDesigner;
                if (boxDesigner == null) { return snapLines; }
    
                foreach (SnapLine line in boxDesigner.SnapLines)
                {
                    if (line.SnapLineType == SnapLineType.Baseline)
                    {
                        snapLines.Add(new SnapLine(SnapLineType.Baseline,
                            line.Offset + control.textBoxValue.Top,
                            line.Filter, line.Priority));
                        break;
                    }
                }
            }
    
            return snapLines;
        }
    }
    

    This way it's actually creating a temporary sub-designer for the subcontrol in order to find out where the "real" baseline snapline is.

    This seemed reasonably performant in testing, but if perf becomes a concern (and if the internal textbox doesn't move) then most of this code can be extracted to the Initialize method.

    This also assumes that the textbox is a direct child of the UserControl. If there are other layout-affecting controls in the way then the offset calculation becomes a bit more complicated.

提交回复
热议问题