views:

301

answers:

2

I need to display text with colors and formatting in a List. I'm using a ListBox with a RichTextControl to display the data. I also need the contents to size to the window, but the text does not need to wrap.

When I make this simple example the text appears vertical and doesn't change as I size the window. If I set the Width of the RichTextBox to a fixed size like 100 then it works.

Any ideas?

<Window x:Class="WpfApplication19.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>
        <ListBox HorizontalContentAlignment="Stretch">
            <ListBox.Items>
                <RichTextBox>
                    <FlowDocument>
                        <Paragraph>
                            <Run>this is a  test</Run>
                        </Paragraph>
                    </FlowDocument>
                </RichTextBox>
            </ListBox.Items>                
        </ListBox>
    </Grid>
</Window>

If there is a better option for displaying text were parts of the text are different colors please let me know.

+1  A: 

If you don't need the list selection behaviour of the ListBox, then using a ItemsControl provides correct layout:

<Grid>
 <ItemsControl>
  <RichTextBox>
   <FlowDocument>
    <Paragraph >
     <Run>this is a  test</Run>
    </Paragraph>
   </FlowDocument>
  </RichTextBox>
 </ItemsControl>
</Grid>

The but to get what you asked for, wrap RichTextBox in the Grid and then Bind to it's ActualWidth

<Grid>
 <ListBox HorizontalContentAlignment="Stretch">
  <ListBox.Items>
   <Grid>
    <RichTextBox Width="{Binding Path=ActualWidth, RelativeSource={RelativeSource AncestorType=Grid}}" >
     <FlowDocument>
      <Paragraph>
       <Run>this is a  test</Run>
      </Paragraph>
     </FlowDocument>
    </RichTextBox>
   </Grid>
  </ListBox.Items>
 </ListBox>
</Grid>
Simeon Pilgrim
Any idea why you need to set the width on the RichTextBox when it is inside a listbox item?
Wallstreet Programmer
I am not sure what about the ListBox's interaction with the RichTextBox is causing this problem/requirement.
Simeon Pilgrim
You can also use a ScrollViewer with a StackPanel in it, then just manage the children. This is what I ended up doing, but I prefer the ItemsControl solution you posted here.
Kelly
An interesting issue I discovered with this: If you set a margin on the RichTextBox, typing into it becomes extremely laggy, because it's calculating the actual width of the `Grid` and updating the `RichTextBox` with the new value at every keystroke.
Robert Rossney
A: 

Thanx for the tip on the ActualWidth, it did the jobs. Gili

Gili