简体   繁体   中英

WP7 Have the enter key send text from textbox to a textblock

The following tutorial shows how to take the text from a text box and display it in a text block when the user hits a button. Simple enough... but what I want to do is instead of hitting a button that adds the text I want the enter button to do it.

Searching here, I found the following code but it doesn't seem to do anything.

private void textBox_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            listBox.Items.Add(textBox.Text);
        }
    }

So, the textbox that has the string is called textbox and I want the text from that textbox to be added to my list (listBox). When I click the enter button, it does nothing. Any help?

You can intercept the enter key from the on screen keyboard, but not from the keyboard of a PC running the emulator.

Here's some code to prove it works:

Create a new Phone Application. Add the following to the content grid

<ListBox Height="276" HorizontalAlignment="Left" Margin="14,84,0,0" Name="listBox1" VerticalAlignment="Top" Width="460" />

Then in the code behind, add the following:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        this.listBox1.Items.Add(textBox1.Text);
    }
}

You'll need to wire this event handler to the textboxes KeyDown event if you haven't done so already. You can do so via the Events tab in the properties window, while the textbox is targeted - or you can double click there and VS will create a new event handler for you which you can put the above code into.

@Court from the answer you gave @Trees i can assume you are not really sure if the KeyDown is wired. Do you have the following code in the XAML file?

<TextBox Height="32" HorizontalAlignment="Left" Margin="13,-2,0,0" Name="textBox1" Text="" VerticalAlignment="Top" Width="433" KeyDown="textBox1_KeyDown" />

@Matt Lacey intercepting Enter from the PC's keyboard also works

看起来您需要改为处理 KeyUp 事件。

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