BrianKE BrianKE -4 years ago 136
C# Question

WPF TextBox disable break on special characters

I have a

TextBox
defined like this:

<TextBox Text="{Binding License.LicenseKey}"
HorizontalContentAlignment="Left"
TextAlignment="Justify"
Width="350"
Height="100"
Margin="10,0,0,0"
TextWrapping="Wrap" />


Currently a long string will break on special characters:

enter image description here

I would prefer it to simply break on any character once it reaches the end of the
TextBox
like this:

enter image description here

Is there a way to disable the stock breaking that a
TextBox
uses? I have tried various options for
TextAlignment
and
HorizontalContentAlignment
to no avail.

Answer Source

You could add a zero-width space (U+200B) after each character which would allow a break at any position. So would need do define a property in your view model, you would to and whose getter would do this transformation, e.g.:

string SomeProperty
{
  get { return String.Join(string.Empty, License.LicenseKey.Zip(new string('\u200B', License.LicenseKey.Length), (x, y) => x.ToString() + y)); }
  set { Model.LicenseKey = value?.Replace("\u200B", string.Empty); }
}

, so that it is displayed with line breaks. However I don't know what would happen to the cursor position.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download