RichTextBox in WPF not resizing contents correctly
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 wo开发者_如何学Crks.
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.
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>
This is an old question, but the issue can be resolved by setting ScrollViewer.HorizontalScrollBarVisibility="Disabled"
. This has to do with ListBox
using a ScrollViewer
internally and how it interacts with RichTextBox
.
<Grid>
<ListBox HorizontalContentAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
<ListBox.Items>
<RichTextBox>
<FlowDocument>
<Paragraph>
<Run>this is a test</Run>
</Paragraph>
</FlowDocument>
</RichTextBox>
</ListBox.Items>
</ListBox>
</Grid>
精彩评论