Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event handler in DataTemplate

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?

like image 218
levanovd Avatar asked Nov 25 '09 23:11

levanovd


People also ask

What is an event handler in Java?

Event handling in Java is the procedure that controls an event and performs appropriate action if it occurs. The code or set of instructions used to implement it is known as the Event handler. It consists of two major components: the event source and the event listener.

What do you understand by event handling explain?

What is Event Handling? Event Handling is the mechanism that controls the event and decides what should happen if an event occurs. This mechanism have the code which is known as event handler that is executed when an event occurs.

What are events in WPF?

WPF input events are generally implemented as a preview and bubbling pairs. Direct: Only event handlers on the event source are invoked. This non-routing strategy is analogous to Windows Forms UI framework events, which are standard CLR events.


2 Answers

You can use the EventSetter in the style you are setting the template with:

<Style TargetType="{x:Type ListBoxItem}">
      <EventSetter Event="MouseWheel" Handler="GroupListBox_MouseWheel" />
      <Setter Property="Template" ... />
</Style>
like image 159
ezolotko Avatar answered Oct 03 '22 07:10

ezolotko


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);
            }
        }
    }
} 
like image 41
levanovd Avatar answered Oct 03 '22 07:10

levanovd