简体   繁体   中英

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?

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").

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

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

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.

Well, Im preaty new to Silverlight and I created HitEnter beahaviour for button which have one DependencyProperty Button.

And I manulay wire up Button and Behavior (in code behind) and then when enter is hit I inovke the command on the button.

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