简体   繁体   English

多行问题WPF TextBox

[英]Multiline issue WPF TextBox

I creating multiline TextBox with this Link its work better but if I want to set TextBox text counter 我使用此链接创建多行TextBox更好,但如果我想设置TextBox文本计数器

label1.Content = textBox1.Text.Length;

with above line work fine but problem is that when I press enter in the TextBox counter it will increase 2 characters in TextBox counter. 上面的行工作正常,但问题是,当我在TextBox计数器中按Enter键时,它将在TextBox计数器中增加2个字符。

How can I do this task please help me. 我怎么能做这个任务请帮帮我。

Any help appreciated! 任何帮助赞赏!

Andrey Gordeev's answer is right (+1 for him) but does not provide a direct solution for your problem. Andrey Gordeev的答案是对的(对他来说是+1),但没有为你的问题提供直接的解决方案。 If you check the textBox1.Text string with the debugger you would see the referred \\r\\n characters. 如果使用调试器检查textBox1.Text字符串,您将看到引用的\\r\\n字符。 On the other hand, if you intend to affect them directly (via .Replace , for example), you wouldn't get anything. 另一方面,如果你打算直接影响它们(例如通过.Replace ),你就不会得到任何东西。

Thus, the practical answer to your question is: rely on Environment.NewLine . 因此,您的问题的实际答案是:依赖Environment.NewLine Sample code: 示例代码:

label1.Content = textBox1.Text.Replace(Environment.NewLine, "").Length;

That's because newline is presented by two symbols: \\r and \\n 那是因为换行符由两个符号表示: \\r\\n

Related question: What is the difference between \\r and \\n? 相关问题: \\ r和\\ n有什么区别?

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;  
        }
    }

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;添加using System.Text;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM