Baseline snaplines in custom Winforms controls(自定义 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 控件中的基线对齐线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:自定义 Winforms 控件中的基线对齐线
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01