Search code examples
c#wpfxamlmvvm

WPF Textblock With Bound Text Will Not Scroll


The text in my TextBlock is bound to an element in my code. However, when I first open my window, the Textblock is completely empty. As I add text, I need the ScrollViewer to allow me to scroll down the text, or automatically scroll down as more text is added. Using the MVVM, so no code behind would be ideal.

<StackPanel Grid.Column="0" Grid.Row="1" Margin="0 10">
    <Label Style="{StaticResource LabelStyle}">Output</Label>
    <ScrollViewer VerticalScrollBarVisibility="Visible" Height="100">
        <TextBlock ScrollViewer.CanContentScroll="True" Height="100" VerticalAlignment="Stretch" TextWrapping="Wrap" Text="{Binding Path=ProcessingOutput}"/>
    </ScrollViewer>
</StackPanel>

How can I make this happen? Is there a way to update the ScrollViewer so that it sees more text is beyond what I can see in the TextBlock and allows the user to scroll down, or allows me to set an autoscroll feature that scrolls down automatically as text is added via binding?

Thanks in advance!


Solution

  • scrollbar will work if you remove Height="100" from TextBlock

    to make it scroll when Text changes other answers suggest to use ScrollViwer.ScrollToBottom() method, e.g. like this:

    <ScrollViewer Name="scroll"
                  VerticalScrollBarVisibility="Visible" 
                  Height="100">
        <TextBlock ScrollViewer.CanContentScroll="True" 
                   VerticalAlignment="Stretch" 
                   TextWrapping="Wrap" 
                   Text="{Binding Path=ProcessingOutput, NotifyOnTargetUpdated=True}"
                   TargetUpdated="Txt_OnTargetUpdated">
            </TextBlock>
    </ScrollViewer>
    
    private void Txt_OnTargetUpdated(object sender, DataTransferEventArgs e)
    {
        scroll.ScrollToBottom();
    }