I am using a WPF Combobox and performing operations on the SelectionChanged
event. I'm also changing the collections from code-behind and do not want the code in the SelectionChanged
event to be triggered then. As such, I am using the IsDropDownOpen
property to determine if the dropdown source was changed using the code or by a user from the application. This works fine when I use the mouse to select values in the dropdown, however, if I use the keyboard to select values and press the Enter key, the event is fired but the IsDropDownOpen
property is false
. I am therefore unable to correctly determine whether the dropdown selection is changed using the code or the application.
The code is as below.
<ComboBox SelectionChanged="Company_SelectionChanged"
DisplayMemberPath="Name" Tag="OrgGroupId"
ItemsSource="{Binding CompanyCollection,UpdateSourceTrigger=PropertyChanged}"
SelectedValue="{Binding SelectedCompany,UpdateSourceTrigger=PropertyChanged}"
x:Name="cmbCompany" />
The selection changed even is as below.
private void Company_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cmbCompany.IsDropDownOpen)
{
/*do something here*/
}
}
How can I correctly determine when the dropdown selection is changed using the application and block the code from executing when it is changed through code?
UPDATE
I managed to get the code working by adding a check for the IsSelectionBoxHighlighted
property. This property returns true whenever a user is using the dropdown to select values, irrespective of whether a mouse or a keyboard is used. The modified code is as below.
private void Company_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cmbCompany.IsDropDownOpen || cmbCompany.IsSelectionBoxHighlighted)
{
/*do something here*/
}
}
I could not find a lot of information on the IsSelectionBoxHighlighted
property online. Can this lead to other errors? Or are there any particular scenarios when this property is set/reset?