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?
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With