C#/WPF: Disable Text-Wrap of RichTextBox

Viewed 30964

Does anyone know how I can disable the text wrapping of a RichTextBox? E.g. if I have a large string which doesn't fit in the window, the RichTextBox places the part of the string which can't be shown of a new line. I want to disable that (and make it visible only by using the Scrollbar).

Thanks a lot.

Cheers

6 Answers

Since no answer was satisfying for me, here is my solution:

private void RichTxt_TextChanged(object sender, TextChangedEventArgs e)
{
    string text = new TextRange(richTxt.Document.ContentStart, richTxt.Document.ContentEnd).Text;
    FormattedText ft = new FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, new Typeface(richTxt.FontFamily, richTxt.FontStyle, richTxt.FontWeight, richTxt.FontStretch), richTxt.FontSize, Brushes.Black);
    richTxt.Document.PageWidth = ft.Width + 12;
    richTxt.HorizontalScrollBarVisibility = (richTxt.Width < ft.Width + 12) ? ScrollBarVisibility.Visible : ScrollBarVisibility.Hidden;
}

Question is about performance depending on text length and how often it is refreshed.

VerticalScrollBar :

VerticalScrollBarVisibility="Auto" MaxHeight="200"

HorizontalScrollBar :

HorizontalScrollBarVisibility="Auto" MaxWidth="400"

Suitable solution for me. The idea was taken from here. I defined in XAML

            <RichTextBox x:Name="PART_rtb" VerticalAlignment="Stretch" ScrollViewer.HorizontalScrollBarVisibility="Auto" TextChanged="MyRichTextBox_OnTextChanged">
                <RichTextBox.Document>
                    <FlowDocument x:Name="PART_fd"  >
                        <FlowDocument.Resources>
                            <!--This style is used to set the margins for all paragraphs in the FlowDocument to 0.-->
                            <Style TargetType="{x:Type Paragraph}">
                                <Setter Property="Margin" Value="3"/>

                            </Style>
                        </FlowDocument.Resources>
                    </FlowDocument>
                </RichTextBox.Document>
            </RichTextBox>

In Code

   private void MyRichTextBox_OnTextChanged(object sender, TextChangedEventArgs e)
    {
        double i  = PART_rtb.Document.GetFormattedText().WidthIncludingTrailingWhitespace + 20;
        (sender as RichTextBox).Document.PageWidth = i;
    }
Related