如何在ToolStripItemCollection中对项目进行排序?

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)

因此,这些项目不是一次性添加的,而是根据程序会话期间的外部触发器逐个添加的。我希望每次添加新项目时都能对下拉列表进行排序。我有哪些选项可以实现这一点?

3个回答

7

由于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

您需要使用自己的比较器 (https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist.sort)。


看起来不错,但我遇到了异常:<code>failed to compare two elements in the array - at least one object must implement icomparable.</code> 这是指对象类本身吗?ToolStripMenuItem?我会看看是否理解自定义比较器。 - bretddog
哦,抱歉,你必须使用自己的比较器,因为ToolStripMenuItem没有比较器,所以数组不知道如何排序。我已经更新了上面的代码。 - SpeziFish
太酷了!我可能会为此苦恼.. 干杯! - bretddog

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);
    }
}

0
如果我们需要对ToolStripItemCollection中的项目进行排序,可以使用以下方法:
ItemCollection.OfType<ToolStripItem>().OrderBy(x => x.Text).ToArray(); 

我猜你的意思是 ItemCollection = ...?但这样做不起作用,因为 DropDownItems 属性是只读的。 - Raphael Smit

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接