我通过以下方式动态地将字符串(项)添加到ToolStripItemCollection:
Dim onClickHandler As System.EventHandler = New System.EventHandler(AddressOf Symbol_Click) Dim item As New ToolStripMenuItem(newSymbol,Nothing,onClickHandler) SomeToolStripMenuItem.DropDownItems.Add(item)
因此,这些项目不会一次性添加,而是在整个程序会话中基于外部触发器逐个添加.我想在每次添加新项目时对下拉列表进行排序.我有什么选择来实现这一目标?
解决方法
由于ToolStripItemCollection没有“Sort”函数,因此您必须监听更改并编写自己的排序方法:
Private Sub ResortToolStripItemCollection(coll As ToolStripItemCollection) Dim oAList As New System.Collections.ArrayList(coll) oAList.Sort(new ToolStripItemComparer()) coll.Clear() For Each oItem As ToolStripItem In oAList coll.Add(oItem) Next End Sub Private Class ToolStripItemComparer Implements System.Collections.IComparer Public Function Compare(x As Object,y As Object) As Integer Implements System.Collections.IComparer.Compare Dim oItem1 As ToolStripItem = DirectCast(x,ToolStripItem) Dim oItem2 As ToolStripItem = DirectCast(y,ToolStripItem) Return String.Compare(oItem1.Text,oItem2.Text,True) End Function End Class
你必须使用自己的比较器(http://msdn.microsoft.com/en-us/library/0e743hdt.aspx)