首页 > 解决方案 > WPF:TextBox中边框和文本之间的空间

问题描述

我有一个宽度等于字母“A”的宽度的文本框。但是字母显示不正确。

是否可以避免边框和“A”开头之间的空格?Padding="0"没有帮助。

例子:

例子

标签: wpf

解决方案


当您使用 Snoop 之类的工具检查可视化树时,您可以看到其中包含TextBox渲染实际内容的内容(1)内部类处理文本框中内容的渲染,默认情况下设置左右边距到“2”(2)。我不认为您可以设置自身的样式来覆盖默认边距值,但由于它在内部设置为“2”,您可以放心地将 Textbox 上的 Padding 设置为“-2,0”就可以了。BorderScrollViewerScrollContentPresenterTextBoxTextBoxViewTextBoxView

编辑:

TextBoxView 文档 中,您可以发现在TextBoxView构造函数(第 38 行)中,Margin 属性设置为BidiCaretIndicatorWidth(第 1219 行)的常量值:因此,在 TextBox 的末尾和开头留一些空间可能是有意义的,因此插入符号可以可见

static TextBoxView()
{
// Set a margin so that the bidi caret has room to render at the B edges of content.
   MarginProperty.OverrideMetadata(typeof(TextBoxView), new FrameworkPropertyMetadata(new Thickness(CaretElement.BidiCaretIndicatorWidth, 0, CaretElement.BidiCaretIndicatorWidth, 0)));
}

(...)
// BiDi caret indicator width.
internal const double BidiCaretIndicatorWidth = 2.0;

在此处输入图像描述


推荐阅读