简体   繁体   中英

Large TextBlock works much faster when placed inside a ViewBox

Accidentialy found a strange behaviour. A large TextBlock, containing 100k lines, is rendered very slow, resizing and scrolling it takes about a second. But if this TextBlock is placed within a ViewBox with Stretch="None" it is scrolled and resized quite fast.

Something in background is definitely changed with a ViewBox, but what and why?

Window contents

    <Grid>
        <ScrollViewer>
            <Viewbox Stretch="None">
                <TextBlock x:Name="TextContainer" HorizontalAlignment="Left" TextAlignment="Left" TextWrapping="Wrap"  VerticalAlignment="Center"/>
            </Viewbox>
        </ScrollViewer>
    </Grid>

Code behind, just creating some text

public MainWindow()
{
    InitializeComponent();

    StringBuilder sb = new StringBuilder();
    for(int i = 1; i < 100000; i++)
    {
        sb.AppendLine($"Line #{i} ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    }
    this.TextContainer.Text = sb.ToString();
}

Presence of a ScrollView have no effect it is still slow without a ViewBox and fast with it. If I change TextBlock to a TextBox with the same content performance becomes fast in all cases. So it is TextBox specific.

Little update: Clarification. I do not need to display large text amounts with a TextBlock, TextBox or [insert whatever you want]. All I want, is to understand, why it behaves like this? Perhaps this knowledge will help me to find solutions to later quiestions, avoid some troubles or just quench my thirst for knowledge. While I appreciate advices on performance optimizations, it does not answer the question.

When you use a ViewBox , the layout and the rendering is done only once , then, it's only an image that is clipped by the ScrollViewer .

Without the ViewBox , the layout is recalculated at each change (scroll, resize, ...). Which causes a slowdown. Maybe it's possible do disable some virtualization but I'm not sure.

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