Mixing RichEditBox with ScrollViewer

Posted by Matt | Filed under , , ,

I was creating an application where I wanted to add a RichEditBox inside a ScrollViewer.  The window containing the ScrollViewer was resizable, so I wanted the ScrollViewer to resize.  Thusly, I wanted the RichEditBox to resize as well.

What I attempted was this:

<Window x:Class="RichTextViewScrollerView.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <ScrollViewer HorizontalScrollBarVisibility="Auto"
                      VerticalScrollBarVisibility="Auto">
            <RichTextBox />
        </ScrollViewer>
    </Grid>
</Window>

However, once I ran the application and started typing, I got this:

image

I tried giving a MinWidth to the RichTextBox, that helped, but it would wrap at that width:  not the full width of the window.

The problem is a bit of a chicken and an egg problem:  the ScrollViewer doesn’t have a width until it’s children have a width, and the RichTextBox doesn’t have a width until it’s parent tells it how much space it can take up.

Since I only needed to have the ScrollViewer scroll vertically, I set HorizontalScrollBarVisibility=”Disabled” and the RichTextBox worked properly.  This was because the ScrollViewer now has a defined width.

image

Comments are closed