【问题标题】:How to make DataGridViewComboBoxColumn selections alignment center?如何使 DataGridViewComboBoxColumn 选择对齐中心?
【发布时间】:2018-08-10 02:02:01
【问题描述】:

我想在编辑模式下(单击下拉菜单时)对齐 DataGridViewComboBoxColumn 选择文本中心。我在这里找到了一种方法:Align Text in Combobox,来对齐组合框,并尝试将EditingControlShowing 事件添加到 DGV,并像上面的方法一样添加DrawItem 事件来对齐组合框,但它不起作用。代码如下:

private void MyDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        ComboBox cb = e.Control as ComboBox;
        if (cb != null)
        {
            cb.DrawItem += new DrawItemEventHandler(cbxDesign_DrawItem);
        }
    }
}
private void cbxDesign_DrawItem(object sender, DrawItemEventArgs e)
{
    // By using Sender, one method could handle multiple ComboBoxes
    ComboBox cbx = sender as ComboBox;
    if (cbx != null)
    {
        // Always draw the background
        e.DrawBackground();

        // Drawing one of the items?
        if (e.Index >= 0)
        {
            // Set the string alignment.  Choices are Center, Near and Far
            StringFormat sf = new StringFormat();
            sf.LineAlignment = StringAlignment.Center;
            sf.Alignment = StringAlignment.Center;

            // Set the Brush to ComboBox ForeColor to maintain any ComboBox color settings
            // Assumes Brush is solid
            Brush brush = new SolidBrush(cbx.ForeColor);

            // If drawing highlighted selection, change brush
            if ((e.State & DrawItemState.Selected) == DrawItemState.Selected)
                brush = SystemBrushes.HighlightText;

            // Draw the string
            e.Graphics.DrawString(cbx.Items[e.Index].ToString(), cbx.Font, brush, e.Bounds, sf);
        }
    }
}

有什么建议吗?谢谢!

【问题讨论】:

  • 你知道你可以在Winforms中使用WPF控件吗? WPF 控件提供更多样式、格式选项
  • 您似乎漏掉了答案的一部分:诀窍是将 ComboBox 的 DrawMode-Property 设置为 OwnerDrawFixed 并订阅其事件 DrawItem。

标签: c# winforms datagridviewcomboboxcolumn


【解决方案1】:

在您的代码中,您需要添加这些属性才能使代码正常工作:

private void MyDGV_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
    if (e.Control.GetType() == typeof(DataGridViewComboBoxEditingControl))
    {
        ComboBox cb = e.Control as ComboBox;
        if (cb != null)
        {
            //add these 2
            cb.DrawMode = DrawMode.OwnerDrawFixed;
            cb.DropDownStyle = ComboBoxStyle.DropDownList;
            cb.DrawItem += new DrawItemEventHandler(cbxDesign_DrawItem);
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-05-17
    • 1970-01-01
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多