简体   繁体   中英

Remove WPF FlowDocument left padding?

I'm attempting to align a flow document to the left with no padding, so that it matches exactly what you see in a TextBlock. I've recreated a simple example of what I'm basically trying to achieve. Here's what I have so far:

<Grid>
    <TextBlock Foreground="Red" Height="Auto" TextWrapping="Wrap"
            Margin="0" Padding="0" FontSize="50" FontFamily="Arial"
            Text="Some text."/>
    <RichTextBox BorderThickness="0" Background="Transparent" BorderBrush="Transparent" IsInactiveSelectionHighlightEnabled="False" HorizontalScrollBarVisibility="Disabled" VerticalScrollBarVisibility="Disabled"
            Height="Auto"
            Margin="0" Padding="0" FontSize="50" FontFamily="Arial" >
        <FlowDocument PagePadding="0" LineStackingStrategy="BlockLineHeight">
            <Paragraph Margin="0" Padding="0" TextIndent="0">Some text.</Paragraph>
        </FlowDocument>
    </RichTextBox>
</Grid>

Here's the result:

在此处输入图像描述

As you can see, the red is the TextBlock version and the black is the RichTextBox/FlowDocument version. The FlowDocument text is offset by about 5 pixels to the right. I've tried to remove all padding that I am aware of, but I still can't get rid of that offset. Any help is appreciated.

NOTE: This question is found as duplicate of WPF: How to make RichTextBox look like TextBlock?

This offset is related to the caret implementation in the RichTextBox control.

Look at.Net 4.8 source, in the RichTextBox.cs file:

// Allocates the initial render scope for this control.
internal override FrameworkElement CreateRenderScope()
{
    FlowDocumentView renderScope = new FlowDocumentView();
    renderScope.Document = this.Document;

    // Set a margin so that the BiDi Or Italic caret has room to render at the edges of content.
    // Otherwise, anti-aliasing or italic causes the caret to be partially clipped.
    renderScope.Document.PagePadding = new Thickness(CaretElement.CaretPaddingWidth, 0, CaretElement.CaretPaddingWidth, 0);

    // We want current style to ignore all properties from theme style for renderScope.
    renderScope.OverridesDefaultStyle = true;

    return renderScope;
}

And the CaretElement.CaretPaddingWidth definition in the CaretElement.cs file:

// Caret padding width to ensure the visible caret for Bidi and Italic.
// Control(TextBox/RichTextBox) must have the enough padding to display
// BiDi and Italic caret indicator.
internal const double CaretPaddingWidth = 5.0;

Therefore, the only option that you can check is set the RichTextBox margin to Margin="-5,0,0,0" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM