简体   繁体   中英

Add text when press return in wpf TextBox

I have a TextBox Which have 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. Step 2: add a "-" to the TextBox's .text .

Hook on PreviewKeyDown event :

<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. (Note: with accepts return KeyDown is not triggered its handled by the text box.)

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:

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

To use this method you'll have to false Accept Return property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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