Search code examples
c#xamlwindows-phonewin-universal-app

How to implement scrolling in a RichTextBlock in Windows Phone


I have a Windows Phone Universal app that has a RichTextBlock which loads its content dynamically. Sometimes the content is short and sometimes its too long to fit in a page; hence, I would like the RichTextBlock to expand dynamically and give the user the ability to scroll to see the entire content.

I looked around (here and other places) for piece of code that achieves this, but was not very successful. The closest I got was the following code that doesn't work:

<ScrollViewer Width="Auto" Height="Auto" VerticalScrollBarVisibility="Visible" VerticalScrollMode="Enabled">
    <RichTextBlock FontSize="20" Foreground="White" IsTextSelectionEnabled="False" Margin="12,0" ScrollViewer.VerticalScrollBarVisibility="Visible">
        <Paragraph>
            Place a very long text here.
        </Paragraph>
    </RichTextBlock>
</ScrollViewer>

Any help is appreciated.


Solution

  • This will work:

    <ScrollViewer Height="150" Width="150">
        <RichTextBlock>
            <Paragraph>This is my RichTextblock</Paragraph>
        </RichTextBlock>
    </ScrollViewer>
    

    The trick here is to fix the Height and/or Width (depending on which direction you want to scroll).

    Back to the example in the question; all it needs is an absolute value; e.g., Height="480":

    <ScrollViewer Width="Auto" Height="480" VerticalScrollBarVisibility="Visible" VerticalScrollMode="Enabled">
        <RichTextBlock FontSize="20" Foreground="White" IsTextSelectionEnabled="False" Margin="12,0" ScrollViewer.VerticalScrollBarVisibility="Visible">
            <Paragraph>
                Place a very long text here.
            </Paragraph>
        </RichTextBlock>
    </ScrollViewer>