多行问题 WPF TextBox
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18459908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Multiline issue WPF TextBox
提问by Jay Shukla
I creating multiline TextBoxwith this Linkits work better but if I want to set TextBoxtext counter
我TextBox用这个链接创建多行它的工作更好但是如果我想设置TextBox文本计数器
label1.Content = textBox1.Text.Length;
label1.Content = textBox1.Text.Length;
with above line work fine but problem is that when I press enter in the TextBoxcounter it will increase 2 characters in TextBoxcounter.
上面的行工作正常,但问题是当我在TextBox计数器中按 Enter 时,它会在TextBox计数器中增加 2 个字符。
How can I do this task please help me.
我该如何完成这项任务,请帮助我。
Any help appreciated!
任何帮助表示赞赏!
采纳答案by varocarbas
Andrey Gordeev's answer is right (+1 for him) but does not provide a direct solution for your problem. If you check the textBox1.Textstring with the debugger you would see the referred \r\ncharacters. On the other hand, if you intend to affect them directly (via .Replace, for example), you wouldn't get anything.
Andrey Gordeev 的回答是正确的(他+1),但没有为您的问题提供直接的解决方案。如果您textBox1.Text使用调试器检查字符串,您将看到引用的\r\n字符。另一方面,如果您打算直接影响它们(.Replace例如,通过),您将一无所获。
Thus, the practical answer to your question is: rely on Environment.NewLine. Sample code:
因此,您问题的实际答案是:依靠Environment.NewLine. 示例代码:
label1.Content = textBox1.Text.Replace(Environment.NewLine, "").Length;
回答by vitaliy zadorozhnyy
if you need just one character on "Enter" then you can just handle PreviewKeyDown event on TextBox and paste following handler:
如果您只需要“Enter”上的一个字符,那么您只需处理 TextBox 上的 PreviewKeyDown 事件并粘贴以下处理程序:
private void Txt_OnPreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
var txtBox = e.Source as TextBox;
var selectionStart = txtBox.SelectionStart;
txtBox.Text = txtBox.Text.Insert(selectionStart, "\n");
txtBox.Select(selectionStart + 1, 0);
e.Handled = true;
}
}
回答by Andrey Gordeev
That's because newlineis presented by two symbols: \rand \n
这是因为换行符由两个符号表示:\r和\n
Related question: What is the difference between \r and \n?
相关问题:\r 和\n 有什么区别?
回答by Gisha Ajeesh
Use the code below instead of label1.Content = textBox1.Text.Length;
使用下面的代码代替 label1.Content = textBox1.Text.Length;
label1.Text = textBox1.Text.Replace(Environment.NewLine, "").Length.ToString();
Please don't forget to add using System.Text;
请不要忘记添加 using System.Text;

