Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pressing Enter on TextBox in Silverlight

I am working on a silverlight app that you need to enter information into a textbox and then just hit enter. Well there is no onclick event, that I could find, so what I did was use the onkeypressup event and check if it was the enter key that was pressed if so do "blah".

It just feels like there is a better way to do this. So the question is, is there?

like image 505
Buddy Lindsey Avatar asked Nov 23 '08 20:11

Buddy Lindsey


4 Answers

I thinks that's the way to catch Key.Enter.

Also, you're code will be more readable if you use the KeyDown event instead of the KeyUp event.

If you only care about catching Key.Enter for a single control then your approach is correct.

You can also catch the Key.Enter for a group of related controls by using the KeyDown event of their container ("Event Bubbling").

like image 183
ptio Avatar answered Sep 27 '22 02:09

ptio


Do you really want it in the textbox? I would put a onkeyup handler on the container (e.g. Grid, Canvas) to press the button anywhere on the form.

like image 24
Shawn Wildermuth Avatar answered Sep 25 '22 02:09

Shawn Wildermuth


This will work if you use want to bind the Command property instead of using the Click event. Start by creating an event handler for Click (see below) and then in the KeyUp do:

    private void MyTextBox_KeyUp(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter) SomeButton_Click(this, null);

    }

    private void SomeButton_Click(object sender, RoutedEventArgs e)
    {
        ICommand cmd = SomeButton.Command;
        if (cmd.CanExecute(null))
        {
            cmd.Execute(null);
        }
    }
like image 30
Dublx Avatar answered Sep 28 '22 02:09

Dublx


I use the following implementation when using the command pattern:

private void MyTextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        BindingExpression b = MyTextBox.GetBindingExpression(TextBox.TextProperty); 
        if (b != null)
            b.UpdateSource();

        ICommand cmd = SomeButton.Command;
        if (cmd.CanExecute(null))
            cmd.Execute(null);
    }
}

When you press Enter, the data source of the textbox is not updated and the command uses an old value. Therefore you have to call UpdateSource before executing the command.

Of course you can catch the event on a higher level than the textbox.

like image 42
slfan Avatar answered Sep 25 '22 02:09

slfan