How to: Custom Paint Group Captions

  • 2 minutes to read

The following sample code handles the NavBarControl.CustomDrawGroupCaption event to custom paint the borders around group captions, fill in the background and paint its text. The background is filled in, in various different ways depending upon the state of the group's caption.

The image below shows the look & feel of group captions in the normal, hot tracked and pressed states, respectively.

CustomDraw - GroupCaption

using System.Drawing.Drawing2D;
using DevExpress.Utils.Drawing;
using DevExpress.XtraNavBar.ViewInfo;

private void navBarControl1_CustomDrawGroupCaption(object sender, 
  CustomDrawNavBarElementEventArgs e) {
    Rectangle outerRect = e.RealBounds;
    e.Cache.FillRectangle(Brushes.Orange, outerRect);

    // painting the background
    Rectangle innerRect = outerRect;
    innerRect.Inflate(-1, -1);
    LinearGradientBrush innerBrush;
    if(e.ObjectInfo.State == ObjectState.Hot)
        innerBrush = new LinearGradientBrush(innerRect, Color.PeachPuff, Color.Orange,
            LinearGradientMode.Vertical);
    else if(e.ObjectInfo.State == ObjectState.Normal)
        innerBrush = new LinearGradientBrush(innerRect, Color.Orange, Color.PeachPuff,
            LinearGradientMode.Horizontal);
    else
        innerBrush = new LinearGradientBrush(innerRect, Color.Orange, Color.PeachPuff,
            LinearGradientMode.Vertical);
    using(innerBrush) 
        e.Cache.FillRectangle(innerBrush, innerRect);

    // painting the caption
    using(var outStringFormat = new StringFormat()) {
        outStringFormat.Alignment = StringAlignment.Near;
        outStringFormat.LineAlignment = StringAlignment.Center;
        NavGroupInfoArgs info = e.ObjectInfo as NavGroupInfoArgs;
        e.Cache.DrawString(info.Group.Caption, e.Appearance.Font, Brushes.White,
            innerRect, outStringFormat);
    }

    // prohibiting default painting
    e.Handled = true;
}