Back to Devexpress

How to: Keep Links Sorted

windowsforms-4885-controls-and-libraries-navigation-controls-navigation-bar-examples-layout-how-to-keep-links-sorted.md

latest2.1 KB
Original Source

How to: Keep Links Sorted

  • Nov 13, 2018
  • 2 minutes to read

The NavLinkCollection.SortByCaption method allows you to sort a NavBar group’s links by their captions. The following code shows how to maintain sort order when new links are added to groups.

The CollectionChanged event of a group’s NavBarGroup.ItemLinks collection allows you to respond to the link collection changing.

Note: this event is not raised when a link’s caption is changed. So, the sorting routine will not be called in this case.

csharp
using DevExpress.XtraNavBar;
//...
//Subscribe to the CollectionChanged events for all the navbar's groups
private void Form1_Load(object sender, System.EventArgs e) {
    for(int i = 0; i < navBarControl1.Groups.Count; i++)
        navBarControl1.Groups[i].ItemLinks.CollectionChanged += 
          new CollectionChangeEventHandler(ItemLinks_CollectionChanged);
}

public void ItemLinks_CollectionChanged(object sender, CollectionChangeEventArgs e) {
    if(e.Action == CollectionChangeAction.Add) {
        NavLinkCollection collection = sender as NavLinkCollection;
        collection.SortByCaption();
    }
}
vb
Imports System.ComponentModel
Imports DevExpress.XtraNavBar
'...
'Subscribe to the CollectionChanged events for all the navbar's groups
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
  Handles MyBase.Load
    Dim i As Integer
    For i = 0 To NavBarControl1.Groups.Count - 1
        AddHandler NavBarControl1.Groups(i).ItemLinks.CollectionChanged, _
          New CollectionChangeEventHandler(AddressOf ItemLinks_CollectionChanged)
    Next
End Sub

Public Sub ItemLinks_CollectionChanged(ByVal sender As Object, _
  ByVal e As CollectionChangeEventArgs)
    If e.Action = CollectionChangeAction.Add Then
        Dim collection As NavLinkCollection = sender
        collection.SortByCaption()
    End If
End Sub