By default the items in the C# Combobox are left aligned. Are there any options available to change this justification apart from overriding DrawItem method and setting the combobox drawmode --> DrawMode.OwnerDrawFixed?
Cheers
By default the items in the C# Combobox are left aligned. Are there any options available to change this justification apart from overriding DrawItem method and setting the combobox drawmode --> DrawMode.OwnerDrawFixed?
Cheers
You could just set the control style to RightToLeft = RightToLeft.Yes
if you don't mind the drop widget on the other side as well.
or
set DrawMode = OwnerDrawFixed;
and hook the DrawItem
event,
then something like
private void comboBox1_DrawItem(object sender, DrawItemEventArgs e)
{
if (e.Index == -1)
return;
ComboBox combo = ((ComboBox) sender);
using (SolidBrush brush = new SolidBrush(e.ForeColor))
{
e.DrawBackground();
e.Graphics.DrawString(combo.Items[e.Index].ToString(), e.Font, brush, e.Bounds, new StringFormat(StringFormatFlags.DirectionRightToLeft));
e.DrawFocusRectangle();
}
}
In WPF this would be as easy as specifying an ItemContainerStyle. In Windows Forms it's a little trickier. Without custom drawing, you could set the RightToLeft property on the ComboBox but this would unfortunately also affect the drop down button.
Since Windows Forms uses a native ComboBox, and Windows doesn't have a ComboBox style like ES_RIGHT that affects the text alignment, I think your only option is to resort to owner draw. It would probably be a good idea to derive a class from ComboBox and add a TextAlignment property or something. Then you would only apply your drawing if TextAlignment was centered or right aligned.
You must "DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed" and your own draw method like this.
protected virtual void OnDrawItem(object sender, DrawItemEventArgs e)
{
var comboBox = sender as ComboBox;
if (comboBox == null)
{
return;
}
e.DrawBackground();
if (e.Index >= 0)
{
StringFormat sf = new StringFormat();
sf.LineAlignment = StringAlignment.Center;
sf.Alignment = StringAlignment.Center;
Brush brush = new SolidBrush(comboBox.ForeColor);
if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
{
brush = SystemBrushes.HighlightText;
}
e.Graphics.DrawString(comboBox.Items[e.Index].ToString(), comboBox.Font, brush, e.Bounds, sf);
}
}