3

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

Rumplin
  • 2,703
  • 21
  • 45
  • can't you rely on commanding instead of simulating keypress ? what is actually your requirement ? – Steve B Sep 09 '11 at 10:24

2 Answers2

1

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

ColinE
  • 68,894
  • 15
  • 164
  • 232
1

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.

Steve B
  • 36,818
  • 21
  • 101
  • 174
  • Good solution, but I use MVVM. I want to avoid to hardcode code to UI elements by all means. – Rumplin Sep 09 '11 at 17:44
  • I don't know what do you mean with that last comment – Rumplin Sep 15 '11 at 10:35
  • EventToCommand is a behavior that can fire an ICommand when a specific event occur. EX: The KeyDown event can fire the KeyInputCOmmand of your VM. take a look in this article : http://mvvmlight.codeplex.com/SourceControl/changeset/view/a926e36786ed#GalaSoft.MvvmLight%2fGalaSoft.MvvmLight.Extras%20%28NET35%29%2fCommand%2fEventToCommand.cs – Steve B Sep 15 '11 at 12:09
  • I still don't understant how will this make me move to the next textbox. Calling a command in my view model doesn't solve anything, I still have to hardcode names in xaml for each textbox... – Rumplin Sep 15 '11 at 14:09
  • 1
    Question related: http://stackoverflow.com/questions/1354903/auto-tab-in-silverlight-3#_=_. I've found a simple solution, here: https://gist.github.com/4576803 – Jone Polvora Jan 20 '13 at 05:28