7

默认情况下,C# Combobox 中的项目是左对齐的。除了覆盖 DrawItem 方法和设置组合框绘制模式 --> DrawMode.OwnerDrawFixed 之外,是否有任何选项可用于更改此理由?

干杯

4

3 回答 3

4

RightToLeft = RightToLeft.Yes如果您也不介意另一侧的放置小部件,则可以将控件样式设置为。

或者

设置DrawMode = OwnerDrawFixed;并挂钩DrawItem事件,然后像

    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();
        }
    }
于 2010-06-23T06:26:51.170 回答
2

在 WPF 中,这就像指定 ItemContainerStyle 一样简单。在 Windows 窗体中,它有点棘手。如果没有自定义绘图,您可以在 ComboBox 上设置 RightToLeft 属性,但不幸的是,这也会影响下拉按钮。

由于 Windows 窗体使用本机 ComboBox,并且 Windows 没有像ES_RIGHT这样影响文本对齐的 ComboBox 样式,我认为您唯一的选择是诉诸所有者绘制。从 ComboBox 派生一个类并添加 TextAlignment 属性或其他东西可能是个好主意。然后,只有当 TextAlignment 居中或右对齐时,您才会应用您的绘图。

于 2010-06-23T06:03:23.200 回答
1

您必须像这样“DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed”和您自己的绘图方法。

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);
    }
}
于 2015-07-04T05:54:39.213 回答