6

我通过以下方式将字符串(项目)动态添加到 ToolStripItemCollection:

Dim onClickHandler As System.EventHandler = New System.EventHandler(AddressOf Symbol_Click)
Dim item As New ToolStripMenuItem(newSymbol, Nothing, onClickHandler)
SomeToolStripMenuItem.DropDownItems.Add(item)

所以项目不是一次性添加的,而是在整个程序会话期间根据外部触发逐一添加的。每次添加新项目时,我都想对下拉列表进行排序。我有什么选择来实现这一目标?

4

3 回答 3

7

由于ToolStripItemCollection没有“排序”功能,您必须听取更改并编写自己的排序方法:

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

您必须使用自己的比较器(https://docs.microsoft.com/en-us/dotnet/api/system.collections.arraylist.sort

于 2011-02-24T15:03:25.933 回答
4

这篇文章被标记为 c#,所以我根据 SpeziFish 的回答对其进行了转换。谢谢!

private void ResortToolStripItemCollection(ToolStripItemCollection coll)
    {
        System.Collections.ArrayList oAList = new System.Collections.ArrayList(coll);
        oAList.Sort(new ToolStripItemComparer());
        coll.Clear();

        foreach (ToolStripItem oItem in oAList)
        {
            coll.Add(oItem);
        }
    }

public class ToolStripItemComparer : System.Collections.IComparer
{
    public int Compare(object x, object y)
    {
        ToolStripItem oItem1 = (ToolStripItem)x;
        ToolStripItem oItem2 = (ToolStripItem)y;
        return string.Compare(oItem1.Text, oItem2.Text, true);
    }
}
于 2015-04-24T15:54:18.797 回答
0

如果我们需要对 中的项目进行排序ToolStripItemCollection,我们可以使用以下内容:

ItemCollection.OfType<ToolStripItem>().OrderBy(x => x.Text).ToArray(); 
于 2015-07-01T12:48:57.330 回答