3
votes

How would you simulate a key press in MVVM in a Silverlight project?

I want to simualte the TAB key press when user presses ENTER, so it moves to the next textbox

2
can't you rely on commanding instead of simulating keypress ? what is actually your requirement ?Steve B

2 Answers

1
votes

Simply handle the KeyUp event where you can check which key is pressed. Then, call the Focus method of the next control. Do not forget to set the Handled property to true.

Sample code :

// Handler for TextBox1
private void OnKeyDownHandler(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Return)
    {
        TextBox2.Focus();
        e.Handled = true;
    }
}

You may also consider iterating over all controls, to find the next focusable element, using TabIndex property.

You can even wrap everything in a attachable behavior, in order to simplify the wiring up.

1
votes

It depends what you are trying to achieve here? If you are just trying execute the same code that would be executed when a key is pressed, then just structure your code to allow this!

For automation of UI controls, simulating key and mouse events, see MSDN:

UI Automation of a Silverlight Custom Control