开发者

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?开发者_如何学Python


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


Looks like you need to handle the KeyUp event instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜