简体   繁体   中英

Auto scroll to the end of a Textblock in WPF

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?

I don't think TextBlock s 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.

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>

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