Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture the event when WPF combobox item is click, or selected by Enter key?

Tags:

combobox

wpf

I had tried this for few hours, but it's not working.

I have a combobox, with a few items in there, generated dynamically like a search box.

Now I want to capture an event, when user click on the dropdown menu item, or click on the dropdown menu item.

How to achieve this? I tried to set mouse/keyboard event handler on Combobox, but it only works on the combobox's textbox, not in the dropdown list.

Thanks.

Edit: I forgot to mention that I has custom DataTemplate on my Combobox. I tried another approach which set the event in ComboBox.ItemContainerStyle.

I tried PreviewKeyDown, but it is not captured. Any idea?

like image 647
VHanded Avatar asked Apr 14 '11 04:04

VHanded


2 Answers

I think that what you are looking for is the "SelectionChanged" event. This event is raised as soon as you select an item in the drop down, either by mouse click or by navigating with arrow keys and hit "Enter" (I tried both with success).

       <ComboBox x:Name="cbobox" ItemsSource="{Binding SourceList}" 
              SelectionChanged="cbobox_SelectionChanged">
        <ComboBox.ItemContainerStyle>
            <Style TargetType="{x:Type ComboBoxItem}">
                <Setter Property="Template" >
                    <Setter.Value>
                        <ControlTemplate>
                            <TextBlock Text="{Binding BusinessProperty}"/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ComboBox.ItemContainerStyle>
    </ComboBox>
like image 106
Bruno Avatar answered Sep 21 '22 08:09

Bruno


I also tried this for hours and here is my solution: Subscribe to the KeyUp event.

Somehow this is the only event being fired and that can be used to distinct between mouse and keyboard selection using custom templates.

public override void OnApplyTemplate()
{
        base.OnApplyTemplate();
        KeyUp += OnKeyUp;
}

void OnKeyUp(object sender, KeyEventArgs e)
{
        if (e.Key == Key.Down)
        {...}
        else if (e.Key == Key.Up)
        {...}
        else if(e.Key == Key.Enter)
        {...}
}

Hope this works for you as well.

like image 25
Martin Avatar answered Sep 19 '22 08:09

Martin