目标:选择组合框下拉列表中的项目时发出事件.
问题:但是,如果用户选择与当前正在选择的项目相同的项目,则使用"SelectionChanged",则不会更改选择,因此不会触发此事件.
问题:只要鼠标单击该项目并且正在选择该项目,无论选择的项目如何,我可以使用什么其他事件处理程序(或其他方式)来发布事件.
(澄清:问题是当再次选择相同项目时如何触发"某事".下拉列表中没有重复.场景:第一次选择项目1,关闭下拉列表.然后再次打开下拉框并选择触发某些功能时的第1项.)
解决方案:目前似乎没有直接的解决方案来做到这一点.但根据每个项目,可以有办法解决它.(如果确实有很好的方法,请更新).谢谢.
del*_*io2 20
我有同样的问题,我终于找到了答案:
您需要像这样处理SelectionChanged事件和DropDownClosed:
在XAML中:
<ComboBox Name="cmbSelect" SelectionChanged="ComboBox_SelectionChanged" DropDownClosed="ComboBox_DropDownClosed">
<ComboBoxItem>1</ComboBoxItem>
<ComboBoxItem>2</ComboBoxItem>
<ComboBoxItem>3</ComboBoxItem>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
在C#中:
private bool handle = true;
private void ComboBox_DropDownClosed(object sender, EventArgs e) {
if(handle)Handle();
handle = true;
}
private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) {
ComboBox cmb = sender as ComboBox;
handle = !cmb.IsDropDownOpen;
Handle();
}
private void Handle() {
switch (cmbSelect.SelectedItem.ToString().Split(new string[] { ": " }, StringSplitOptions.None).Last())
{
case "1":
//Handle for the first combobox
break;
case "2":
//Handle for the second combobox
break;
case "3":
//Handle for the third combobox
break;
}
}
Run Code Online (Sandbox Code Playgroud)
对我来说ComboBox.DropDownClosed事件做到了.
private void cbValueType_DropDownClosed(object sender, EventArgs e)
{
if (cbValueType.SelectedIndex == someIntValue) //sel ind already updated
{
// change sel Index of other Combo for example
cbDataType.SelectedIndex = someotherIntValue;
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用"ComboBoxItem.PreviewMouseDown"事件.因此,每当鼠标停在某个项目上时,此事件将被触发.
要在XAML中添加此事件,请使用"ComboBox.ItemContainerStyle",如下例所示:
<ComboBox x:Name="MyBox"
ItemsSource="{Binding MyList}"
SelectedValue="{Binding MyItem, Mode=OneWayToSource}" >
<ComboBox.ItemContainerStyle>
<Style>
<EventSetter Event="ComboBoxItem.PreviewMouseDown"
Handler="cmbItem_PreviewMouseDown"/>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
Run Code Online (Sandbox Code Playgroud)
像往常一样处理它
void cmbItem_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
//...do your item selection code here...
}
Run Code Online (Sandbox Code Playgroud)
感谢MSDN
小智 5
我希望您会发现以下技巧。
您可以绑定两个事件
combobox.SelectionChanged += OnSelectionChanged;
combobox.DropDownOpened += OnDropDownOpened;
Run Code Online (Sandbox Code Playgroud)
并在OnDropDownOpened内部强制将所选项目设置为null
private void OnDropDownOpened(object sender, EventArgs e)
{
combobox.SelectedItem = null;
}
Run Code Online (Sandbox Code Playgroud)
然后使用OnSelectionChanged中的项目执行所需的操作。每次打开组合框时,都会引发OnSelectionChanged,但是您可以检查方法中的SelectedItem是否为null并跳过命令
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (combobox.SelectedItem != null)
{
//Do something with the selected item
}
}
Run Code Online (Sandbox Code Playgroud)