C#/WPF: Disable Text-Wrap of RichTextBox

五迷三道 提交于 2019-12-28 03:04:37

问题


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


回答1:


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.




回答2:


If you don't want to show the horizontal scrollbar, enforce a MinWidth on the ScrollViewer:

<RichTextBox ScrollViewer.HorizontalScrollBarVisibility="Hidden">

    <RichTextBox.Resources>
        <Style TargetType="ScrollViewer">
            <Setter Property="MinWidth" Value="2000" />
        </Style>
    </RichTextBox.Resources>

</RichTextBox>



回答3:


I also needed to display a large string and tried the RichTextBox but I did not like the solution with setting the PageWidth of the Document to a fixed size. The scrollbar would be visible all the time and the scrolling area was be to big.

If a TextBlock is sufficient you can use that instead and place it inside a ScrollViewer. It worked perfect for me since I did not need all the extra features of the RichTextBox.

<ScrollViewer Width="200"
              Height="100"
              HorizontalScrollBarVisibility="Auto"
              VerticalScrollBarVisibility="Auto">
                  <TextBlock TextWrapping="NoWrap">
                      <TextBlock.Text>
                          Very long text Very long text Very long text 
                      </TextBlock.Text>
                  </TextBlock>
</ScrollViewer>


来源:https://stackoverflow.com/questions/1368047/c-wpf-disable-text-wrap-of-richtextbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!