WPF 组合框上的选定索引更改?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14343163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selected Index Change on WPF combobox?
提问by Justin Emlay
I'm converting an app of mine from WinForms to WPF. I came across this problem where in WinForms if I CLEAR a combobox, that does not fire combobox.selectedindexchange. It only fires when the user actually changes the index.
我正在将我的一个应用程序从 WinForms 转换为 WPF。我在 WinForms 中遇到了这个问题,如果我清除了一个组合框,则不会触发 combobox.selectedindexchange。它仅在用户实际更改索引时触发。
That's the functionality I need. However in WPF I can only find combobox.SelectionChanged. This unfortunately fires on both index change and clearing a combobox (any change).
这就是我需要的功能。但是在 WPF 中我只能找到 combobox.SelectionChanged。不幸的是,这会在索引更改和清除组合框(任何更改)时触发。
In WPF how can I only trigger an event when the user changes the index? I'm assuming there's a solution I'm missing that's like the WinForms solution. I'm trying not to play games with global variables and having to track what was previously selected....that's a mess.
在 WPF 中,如何仅在用户更改索引时触发事件?我假设有一个我缺少的解决方案,就像 WinForms 解决方案一样。我试图不玩带有全局变量的游戏,并且不得不跟踪以前选择的内容......这是一团糟。
Mouseleave is also a mess.
Mouseleave 也是一团糟。
I would greatly appreciate any help!
我将不胜感激任何帮助!
回答by Rafal
In your case you can implement in SelectionChangedevent:
在您的情况下,您可以在SelectionChanged事件中实施:
Private Sub OnSelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs)
Dim combo = TryCast(sender, ComboBox)
If combo.SelectedItem IsNot Nothing Then
'do something
End If
End Sub
回答by kmatyaszek
You can remove event handler, invoke clear method and add again event handler.
您可以删除事件处理程序,调用 clear 方法并再次添加事件处理程序。
Example code:
示例代码:
<StackPanel>
<ComboBox Name="myCB"
SelectionChanged="ComboBox_SelectionChanged">
<ComboBoxItem>test1</ComboBoxItem>
<ComboBoxItem>test2</ComboBoxItem>
<ComboBoxItem>test3</ComboBoxItem>
</ComboBox>
<Button Content="Clear" Click="Button_Click" />
</StackPanel>
MainWindow class:
主窗口类:
Class MainWindow
Private Sub ComboBox_SelectionChanged(sender As System.Object, e As System.Windows.Controls.SelectionChangedEventArgs)
Console.WriteLine("Selected index: {0}", CType(sender, ComboBox).SelectedIndex)
End Sub
Private Sub Button_Click(sender As System.Object, e As System.Windows.RoutedEventArgs)
RemoveHandler Me.myCB.SelectionChanged, AddressOf ComboBox_SelectionChanged
Me.myCB.Items.Clear()
AddHandler Me.myCB.SelectionChanged, AddressOf ComboBox_SelectionChanged
End Sub
End Class

