How to: Create a NavBar Control in Code
- 3 minutes to read
The following code shows how to create a NavBarControl in code. One group (Local) is added to the control containing three commands (“Inbox”, “Outbox” and “Sent Items”).
In the example, NavBarItem objects are created to represent the required commands. Their NavElement.Caption properties are initialized appropriately. These specify the display text for the items.
It’s assumed that small images for NavBar items are stored in the imageList1 component. To use these images, the imageList1 is assigned to the NavBarControl.SmallImages property. Then images from the list are associated with specific NavBar items via the item’s NavElement.SmallImageIndex property.
The NavBarControl.BeginUpdate and NavBarControl.EndUpdate methods are used to prevent excessive updates when mutiple control’s properties are modified.
The image below shows the result:
using DevExpress.XtraNavBar;
private void Form1_Load(object sender, EventArgs e) {
// Create a NavBarControl.
NavBarControl navBar = new NavBarControl();
this.Controls.Add(navBar);
navBar.Dock = DockStyle.Fill;
// Apply the "SkinExplorerBarView" style.
navBar.PaintStyleName = "SkinExplorerBarView";
// Assign the list that stores small images to the control.
navBar.SmallImages = imageList1;
// Create a Local group.
NavBarGroup groupLocal = new NavBarGroup("Local");
// Create an Inbox item and assign an image from the SmallImages list to the item.
NavBarItem itemInbox = new NavBarItem("Inbox");
itemInbox.SmallImageIndex = 0;
// Create an Outbox item.
NavBarItem itemOutbox = new NavBarItem("Outbox");
itemOutbox.SmallImageIndex = 1;
// Create a disabled Sent Items item.
NavBarItem itemSentItems = new NavBarItem("Sent Items");
itemSentItems.SmallImageIndex = 2;
itemSentItems.Enabled = false;
// Add the created items to the group and the group to the NavBarControl.
// Prevent excessive updates using the BeginUpdate and EndUpdate methods.
navBar.BeginUpdate();
navBar.Groups.Add(groupLocal);
groupLocal.ItemLinks.Add(itemInbox);
groupLocal.ItemLinks.Add(itemOutbox);
groupLocal.ItemLinks.Add(itemSentItems);
groupLocal.Expanded = true;
navBar.EndUpdate();
// Specify the event handler which will be invoked when any link is clicked.
navBar.LinkClicked += new NavBarLinkEventHandler(navBar_LinkClicked);
}
void navBar_LinkClicked(object sender, NavBarLinkEventArgs e) {
MessageBox.Show(string.Format("The {0} link has been clicked", e.Link.Caption));
}