【问题标题】:Add text when press return in wpf TextBox在wpf TextBox中按回车时添加文本
【发布时间】:2015-05-07 01:30:43
【问题描述】:

我有一个具有 AcceptsReturn = True 的文本框。当用户按下回车键时,新行的第一个字母“-”已经存在。 我该怎么做?

【问题讨论】:

    标签: c# wpf


    【解决方案1】:

    步骤 1:编写一个方法来检测 Key Press 上“Return”键的按下情况。 第 2 步:在 TextBox 的.text 中添加一个“-”。

    【讨论】:

    • 感谢您的帮助^^
    【解决方案2】:

    关注PreviewKeyDown 事件:

    <TextBox PreviewKeyDown="UIElement_OnKeyDown"
             AcceptsReturn="True"
             x:Name="TextBox"
    </TextBox>
    
    
    private void UIElement_OnKeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            // what u need
            // TextBox.Text += "-";
        }
    }
    

    【讨论】:

    • 感谢您的帮助^^
    【解决方案3】:

    可能还有其他更聪明的方法可以做到这一点,但一个简单的解决方案是将 PreviewKeyDown 添加到 TextBox。 (注意:接受返回 KeyDown 不会触发它由文本框处理。)

    PreviewKeyDown="TextBox_KeyDown"
    
     private void TextBox_KeyDown(object sender, KeyEventArgs e)
     {
          if(e.Key == Key.Return)
          {
              (sender as TextBox).Text += "-";
          }
     }
    

    这应该在新行中添加一个 -。

    【讨论】:

    • 感谢您的帮助^^
    【解决方案4】:

    订阅TextBox KeyDown事件并检测Enter是否被按下:

    XAML

    <TextBox ... KeyDown="TextBox_KeyDown"/>
    

    C#

    private void TextBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            TextBox txtBox = sender as TextBox;
            txtBox.Text += Environment.NewLine + "-"; //add new line and "-"
            txtBox.CaretIndex = txtBox.Text.Length;   //caret to the end
        }
    }
    

    要使用此方法,您必须 false Accept Return 属性。

    【讨论】:

    • 当您将 AcceptsReturn 设置为 true 时,按下回车键时不会触发 ...
    • 我已经提到过,你必须false它才能使用这个方法。
    • OP 想在开头添加一个带有- 的新行。这是他的方法,我提供了另一种方法。当解决方案与问题无关时,您应该投反对票。
    • 红色第一句 - “我有一个 TextBox which have AcceptsReturn = True”
    • 我想解决方案是正确的。每个问题都有很多解决方案。你有你的,我有我的。让我们在这里结束,让 OP 做出决定。
    猜你喜欢
    • 2011-10-13
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多