protected override void OnDrawItem(DrawItemEventArgs e) { base.OnDrawItem(e); //Draw original background and selection. //You can remove this and draw your own background if you want. e.DrawBackground(); e.DrawFocusRectangle(); if (e.Index >= 0 && e.Index < Items.Count) { ColorListBoxItem item = Items[e.Index]; if (item != null) { e.Graphics.SmoothingMode = SmoothingMode.HighQuality; if (ShowImages && item.Image != null) { //Draw the image e.Graphics.DrawImage(item.Image, e.Bounds.X, e.Bounds.Y, ItemHeight, ItemHeight); } } //Draw the item text DrawItemText(e, item); } }
private void DrawItemText(DrawItemEventArgs e, ColorListBoxItem item) { float x = 0; float y = 0; SizeF textSize = e.Graphics.MeasureString(item.Text, Font); float w = textSize.Width; float h = textSize.Height; Rectangle bounds = e.Bounds; //If we are showing images, make some room for them and adjust the bounds width. if (ShowImages) { bounds.X += ItemHeight; bounds.Width -= ItemHeight; } //Depending on which TextAlign is chosen, determine the x and y position of the text. switch (TextAlign) { case ContentAlignment.BottomCenter: x = bounds.X + (bounds.Width - w) / 2; y = bounds.Y + bounds.Height - h; break; case ContentAlignment.BottomLeft: x = bounds.X; y = bounds.Y + bounds.Height - h; break; case ContentAlignment.BottomRight: x = bounds.X + bounds.Width - w; y = bounds.Y + bounds.Height - h; break; case ContentAlignment.MiddleCenter: x = bounds.X + (bounds.Width - w) / 2; y = bounds.Y + (bounds.Height - h) / 2; break; case ContentAlignment.MiddleLeft: x = bounds.X; y = bounds.Y + (bounds.Height - h) / 2; break; case ContentAlignment.MiddleRight: x = bounds.X + bounds.Width - w; y = bounds.Y + (bounds.Height - h) / 2; break; case ContentAlignment.TopCenter: x = bounds.X + (bounds.Width - w) / 2; y = bounds.Y; break; case ContentAlignment.TopLeft: x = bounds.X; y = bounds.Y; break; case ContentAlignment.TopRight: x = bounds.X + bounds.Width - w; y = bounds.Y; break; } //Finally draw the text. e.Graphics.DrawString(item.Text, Font, new SolidBrush(item.Color), x, y); }