C#/WPF: Disable Text-Wrap of RichTextBox
A RichTextBox
in WPF is simply an editor for a FlowDocument
.
According to MSDN:
Text always wraps in a RichTextBox. If you do not want text to wrap then set the PageWidth on the FlowDocument to be larger than the width of the RichTextBox. However, once the page width is reached the text still wraps.
So, while there's no way for you to explicitly disable the word-wrapping of a RichTextBox
, you can do something like this:
richTextBox1.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
richTextBox1.Document.PageWidth = 1000;
Which will have essentially the same desired effect until you have a line that exceeds the PageWidth
.
Note (as of July 2015): VS2015 RC allows wordwrap = false
to work precisely as OP seems to desire. I believe earlier versions of Visual Studio did also.
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.