简体   繁体   中英

WPF Combobox SelectionChanged not fired on Enter key down

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?

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?

How about creating a field to track it yourself.

bool _applicationChangingDropdown = false;

Set it to true at the start of any code that you don't want to trigger the SelectionChanged and set it to false after.

Then just use

if(!_applicationChangingDropdown)
{
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM