views:

295

answers:

3

Hi,

I need some help to implement a common behavior in some controls.

In my WPF application, I have a main form that contains a panel and a button:

Ok

The button will run a Save method when clicked.The Save method reads some data from the form and saves the data to a database.

The panel is populated with dynamically created controls (such as textbox, dropdownlists, etc). The main form instantiates a MainViewModel class. This MainViewModel class instantiates a class called UIFactory. So we have 3 levels here.

In the UIFactory class the controls is being created. The Panel from the main form is sent as a parameter to a method in the MainModelView class called GenerateUI. This GenerateUI method in the MainViewModel class calls a GenerateControls method on the UIFactory class that takes the same panel as a parameter. The GenerateControls method in the UIFactory class then adds dynamically created controls on the panel.

What I want to achieve is that whenever the user hits ENTER when he is typing in one of those dynamically created controls e.g a textbox, I want that behavior to be the same as clicking on the button in my main form. But how do I do that? I thought of implementing Routed events on my controls, but I can't figure out how to do it. Could you please advise me on how to achieve my goal?

Best Regards,

OKB

A: 

Maybe the Keyboard.KeyUp attached event might help you. You could set it on the main panel which contains the dynamically created controls and then perform the save operation if the pressed key was the ENTER key.

gehho
A: 

Hi again,

I did manage to create a work aroind to my problem:

What I did was to create a custom user control(let's call it a container). This control is hosted in my wpf application using the WindowsFormsHost instead of the panel. Then I add the dynamically created user control to my new custom user control (the container) and add a KeyEventHandler on each child control's KeyUp event. I created a custom event and event handler in my container that will catch all KeyUp event from the child controls, check if the e.KeyValue == 13 (ENTER) and then raise my custom event from the container that will be handled in my wpf form. Ugly as h*ll, but it works.

OKB