views:

470

answers:

3

I have WPF ComboBox inside a data template (a lot of comboboxes in listbox) and I want to handle enter button. It would be easy if it was e.g. a button - I would use Command + Relative binding path etc. Unfortunately, I have no idea how handle key press with a Command or how to set event handler from template. Any suggestions?

+2  A: 

check out this little 'tutorial' on creating event handlers from WPF data templates:

http://anoriginalidea.wordpress.com/2007/05/23/responding-to-events-from-datatemplate-controls-in-wpf/

Hope it is of some help to you.

Tony
+1  A: 

I've solved my problem by using a usual event handler where I walk through the visual tree, find corresponding button and call it's command. If anybody else has the same problem, please post a comment and I'll provide more details of realization.

UPD

Here is my solution:

I search the visual tree for a button and than execute command associated with button.

View.xaml:

        <ComboBox KeyDown="ComboBox_KeyDown"/>
        <Button Command="{Binding AddResourceCommand}"/>

View.xaml.cs:

        private void ComboBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                var parent = VisualTreeHelper.GetParent((DependencyObject)sender);
                int childrenCount = VisualTreeHelper.GetChildrenCount(parent);

                for (int i = 0; i < childrenCount; i++)
                {
                    var child = VisualTreeHelper.GetChild(parent, i) as Button;
                    if (null != child)
                    {
                        child.Command.Execute(null);
                    }
                }
            }
        } 
levanovd
A: 

HI levanovd, I would like to know the solution!

Sarath
Sarath, I've updated my post so you can find what you need there.
levanovd
Thanks levanovd :) That was helpful :)
Sarath