[英]WPF Combobox SelectionChanged not fired on Enter key down
I am using a WPF Combobox and performing operations on the SelectionChanged
event. 我正在使用WPF组合框并在
SelectionChanged
事件上执行操作。 I'm also changing the collections from code-behind and do not want the code in the SelectionChanged
event to be triggered then. 我也正在从代码隐藏中更改集合,并且不希望随后触发
SelectionChanged
事件中的代码。 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. 这样,我正在使用
IsDropDownOpen
属性来确定下拉源是否已使用代码更改或由用户从应用程序更改。 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
. 当我使用鼠标在下拉菜单中选择值时,此方法工作正常,但是,如果我使用键盘选择值并按Enter键,则将触发事件,但
IsDropDownOpen
属性为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. 我设法通过添加对
IsSelectionBoxHighlighted
属性的检查来使代码正常工作。 This property returns true whenever a user is using the dropdown to select values, irrespective of whether a mouse or a keyboard is used. 每当用户使用下拉列表选择值时,无论使用鼠标还是键盘,此属性都将返回true。 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. 我在网上的
IsSelectionBoxHighlighted
属性上找不到很多信息。 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. 在您不想触发SelectionChanged的任何代码开始时将其设置为true,之后将其设置为false。
Then just use 然后使用
if(!_applicationChangingDropdown)
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.