自定义 Winforms 控件中的基线对齐线基线、自定义、控件、Winforms

2023-09-08 09:28:26 作者:老顽童!

我有一个带有文本框的自定义用户控件,我想在自定义控件之外公开基线(文本框中的文本)对齐线.我知道您创建了一个设计器(从 ControlDesigner 继承)并重写 SnapLines 以访问对齐线,但我想知道如何获取自定义用户控件公开的控件的文本基线.

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 create a designer (inherited from ControlDesigner) and override SnapLines to get access to the snaplines, but I'm wondering how to get the text baseline of a control that I have exposed by my custom user control.

推荐答案

我刚好有类似的需求,我是这样解决的:

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.

这在测试中似乎表现不错,但如果 perf 成为问题(并且如果内部文本框没有移动),那么大部分代码都可以提取到 Initialize 方法中.

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.

这也假定文本框是 UserControl 的直接子级.如果中间还有其他影响布局的控件,那么偏移量的计算就变得有点复杂了.

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.