Right justified combobox in C#

后端 未结 3 1607
独厮守ぢ
独厮守ぢ 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: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);
        }
    }
    

提交回复
热议问题