我的问题是当在C#(WPF)中的ComboBox中选择ComboBoxItem时,如何执行操作?
My question is how to do an action when an ComboBoxItem is Selected in a ComboBox in C# (WPF) ?
在此帖子他们处理DropDownClosed事件,但他们不处理键盘选择。
In this post they handle the DropDownClosed event but they don't handled the keyboard Selection.
所以我解释一下我的情况:
So I explain my case:
ComboBoxItems的Selected事件或ComboBox的SelectionChanged动作只有当用户选择不同的ComboBoxItem,但我想要执行动作,即使用户选择的ComboBoxItem是相同的ComboBoxItem已经选择的相同。
The events "Selected" for the ComboBoxItems or "SelectionChanged" for the ComboBox do the action only when the user select an different ComboBoxItem, but I would like that the action be execute even if the ComboBoxItem that the user select is the same that the ComboBoxItem already selected.
我尝试用PreviewMouseLeftButtonDown,但如果用户用键盘选择或只是保持鼠标按,然后选择,它不工作。
I try with "PreviewMouseLeftButtonDown", but if the user select with keyboard or just keep the mouse press and then select, it doesn't work.
在我的情况下,我选择一个项目时必须打开一个窗口:
In my situation, I have to open a window when I select an Item:
private void cmiCCSelect_Selected(object sender, RoutedEventArgs e) { cCEntityWindow.ShowDialog(); }但是如果用户关闭此窗口并重新选择相同的项目不工作。我必须选择另一个,然后重新选择相同的事件选择可以执行。
But if the user close this window and re-select the same Item, it doesn't work. I have to select an other and after re-select the same for the Event "Selected" can be execute.
任何人都可以帮助我吗?
Can anybody help me?
推荐答案我终于找到了答案:
你需要处理SelectionChanged事件和DropDownClosed像这样:
You need to handle BOTH the SelectionChanged event and the DropDownClosed like this:
在XAML中:
<ComboBox Name="cmbSelect" SelectionChanged="ComboBox_SelectionChanged" DropDownClosed="ComboBox_DropDownClosed"> <ComboBoxItem>1</ComboBoxItem> <ComboBoxItem>2</ComboBoxItem> <ComboBoxItem>3</ComboBoxItem> </ComboBox>在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; } }更多推荐
选择组合框时发生事件
发布评论