Right justified combobox in C#

后端 未结 3 1602
独厮守ぢ
独厮守ぢ 2021-01-12 12:07

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

相关标签:
3条回答
  • 2021-01-12 12:23

    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.

    0 讨论(0)
  • 2021-01-12 12:38

    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();
            }
        }
    
    0 讨论(0)
  • 2021-01-12 12:38

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题