简体   繁体   English

在wpf TextBox中按回车时添加文本

[英]Add text when press return in wpf TextBox

I have a TextBox Which have AcceptsReturn = True . 我有一个具有AcceptsReturn = True的文本框。 When the user press return the new line will already have as the first letter "-". 当用户按下回车键时,新行将以第一个字母“-”开头。 How do I do that? 我怎么做?

Step 1: write a method that detects a press of the "Return" key on the Key Press. 步骤1:编写一种方法来检测按键上是否按下了“ Return”键。 Step 2: add a "-" to the TextBox's .text . 步骤2:在TextBox的.text添加“-”。

Hook on PreviewKeyDown event : 挂接到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 += "-";
    }
}

There could be other smarter ways to do this but a simple solution would be add a PreviewKeyDown to the TextBox. 可能还有其他更聪明的方法来执行此操作,但是一个简单的解决方案是将PreviewKeyDown添加到TextBox。 (Note: with accepts return KeyDown is not triggered its handled by the text box.) (注意:带有接受返回键的KeyDown不会由文本框触发触发。)

PreviewKeyDown="TextBox_KeyDown"

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

This should add a - in the new line. 这应该在新行中添加-。

Subscribe to TextBox KeyDown event and detect if Enter is pressed: 订阅TextBox KeyDown事件并检测是否按下Enter

XAML : XAML

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

C# : 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
    }
}

To use this method you'll have to false Accept Return property. 要使用此方法,您必须将false Accept Return属性。

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

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