Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Textbox and space character wrapping

Tags:

c#

wpf

My Observations:

In testing a WPF application with a Wrap enabled TextBox to allow for multi-lines of text, if I just start typing words and I reach the far right side of the TextBox, words and cursor wrap to the next line based on the last space/break of characters in my typing.

If on the 1st line I type a single character and then hold down the spacebar, the cursor scrolls out of view in the TextBox and does not wrap to the 2nd line when the cursor reaches the end of the 1st line. Once I type something other than a space, that character wraps and starts at the beginning of the 2nd line. If I use the left arrow key to move backwards, the cursor will disappear from the 2nd line and will not be visible for sometime on the 1st line until it moves thru all of the spaces that were previously type. If I place the cursor at the end of the 1st line and type another non-space character, that character generally wraps to the 2nd line with several spaces in front of the previous character on the 2nd line. Relative to the text in the TextBox, the contents will include all of the visible characters plus all the space characters contained outside of the view area of the TextBox.

My Question:

Is there a property setting on the TextBox that I am missing to force the space characters to wrap the 2nd line once they reach the end of the 1st line rather than scrolling off of the screen?

Thanks.

Mark

like image 474
Mark Parr Avatar asked Jul 08 '15 17:07

Mark Parr


1 Answers

Did some research and replacing space " " with nonbreaking space "/u00a0" on text changed keeps the cursor inside the bounds of the textbox.

I simply wired this up as a proof of concept, this will result in recursive calls so don't use this in production code. Maybe use a converter instead, or maybe in your data-bound property setter?

    /// <summary>
    ///     Handle textbox on text changed event
    /// </summary>
    private void TextBoxBase_OnTextChanged(object sender, TextChangedEventArgs e)
    {
        // Replace space with non-breaking space
        TestTextBox.Text = TestTextBox.Text.Replace(" ", "\u00a0");
        // Put the cursor at the end of the textbox (updating text sets the cursor at the start)
        TestTextBox.CaretIndex = TestTextBox.Text.Length;
    }
like image 180
robaudas Avatar answered Oct 06 '22 22:10

robaudas