自定义 Winforms 控件中的基线对齐线 [英] Baseline snaplines in custom Winforms controls

查看:29
本文介绍了自定义 Winforms 控件中的基线对齐线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文本框的自定义用户控件,我想在自定义控件之外公开基线(文本框中的文本)对齐线.我知道您创建了一个设计器(从 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.

这篇关于自定义 Winforms 控件中的基线对齐线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆