Say I have the following:
I have looked at several solutions today. They either don't work at all, or if they work, they don't work the way I think they should. Oddities with cursor position, or wrapping incorrectly. Here is my "solution", and I hope it helps someone in the future. It wraps, doesn't unwrap, and keeps any existing new lines. I set this example to 60 characters wide, and a bool isBusyUpdating outside of this example to keep it from firing again when the update is in progress.
txtNotes.HorizontalContentAlignment = HorizontalAlignment.Left;
txtNotes.VerticalContentAlignment = VerticalAlignment.Top;
txtNotes.TextWrapping = TextWrapping.NoWrap;
txtNotes.AcceptsReturn = true;
txtNotes.TextChanged += delegate (object o, TextChangedEventArgs args)
{
//args.Handled = true;
TextBox thisText = (TextBox)args.Source;
if (!isBusyUpdating)
{
isBusyUpdating = true;
string updatedText = "";
bool blnUpdate = false;
int curPos = thisText.CaretIndex;
foreach (string thisLine in thisText.Text.Split('\n'))
{
if (thisLine.Length > 60)
{
blnUpdate = true;
updatedText = updatedText +
thisLine.Substring(0, 60)
.Replace("\n", "") +
"\n" + thisLine.Substring(60);
curPos++;
}
else
{
updatedText = updatedText + thisLine + "\n";
}
}
if (blnUpdate)
{
thisText.Text = updatedText;
thisText.CaretIndex = curPos-1;
}
isBusyUpdating = false;
}
};