4

I want to view the content of a textblock that was added last. It means I want to auto scroll to the end and view the hidden content when I add more text... just like in Windows calculator.

In the calculator when I enter more numbers it shows only the numbers entered last. Previously entered numbers are hidden when there is not enough space. I want to do the exact same thing..

Can someone please help me?

Claudio
  • 2,191
  • 24
  • 49
Daybreaker
  • 1,037
  • 5
  • 20
  • 42

2 Answers2

17

I don't think TextBlocks can scroll. You can put the TextBlock in a ScrollViewer.

XAML:

<ScrollViewer Name="MyScrollViewer">
    <TextBlock TextWrapping="Wrap">
        A bunch of text
    </TextBlock>
</ScrollViewer>

Code-behind:

MyScrollViewer.ScrollToBottom();

It appears that if you have multiple TextBlocks in a ListBox, you cannot get access very easily to it's ScrollViewer to accomplish the same thing. If you are doing this, change your ListBox to an ItemsControl and put that into a ScrollViewer. I think you'll lose selection ability though.

If you do need to use a ListBox, then you can get the view that belongs to the last item and call the ListBox's ScrollIntoView() method. See this or this for a little bit about that, but you might have to do a little more research.

Community
  • 1
  • 1
Steve
  • 6,334
  • 4
  • 39
  • 67
1

Do you mean a TextBox, as opposed to a TextBlock? The default behavior for a TextBox is to show the most recent text as more text is entered.

Window x:Class="textboxscrolltest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <TextBox Width="75" Height="25"/>
    </Grid>
</Window>
Sean Beanland
  • 1,098
  • 1
  • 10
  • 25
  • 1
    Not working for me. I am using it as console and appending text to it from logs. but its not scrolling automatically – Kundan Jul 08 '20 at 11:13
  • 1
    The question is about TextBlock as main stream output UI element where scrolling is very appreciated – Sergey Orlov Sep 03 '21 at 13:41