【问题标题】:Right justified combobox in C#C#中的右对齐组合框
【发布时间】:2011-03-07 03:53:06
【问题描述】:

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

干杯

【问题讨论】:

  • 我在您的问题中添加了 winforms 标记,因为我假设您提到 DrawItem 并不是指 WPF。虽然这与 C# 没有任何关系,但我不想删除标签。

标签: c# .net winforms combobox text-alignment


【解决方案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);
    }
}

【讨论】:

    【解决方案2】:

    如果您不介意另一边的拖放小部件,您可以将控件样式设置为 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();
            }
        }
    

    【讨论】:

    • 嗨......即使在我实现了这个处理程序之后,我也看不到任何区别。
    • 不知道为什么,你记得把组合框DrawMode的属性设置为OwnerDrawFixed。列表中有一些项目吗?
    【解决方案3】:

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

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

    【讨论】:

    • 嗨......在这种情况下,我如何将 TextAlignment 应用于控件?你是在暗示这里的字符串格式吗?
    • 不,我是说您需要创建一个从 ComboBox 派生的控件并添加一个名为 TextAlignment 的 new 属性。然后在你的 OnDrawItem 方法中,你可以考虑这个属性,而不是硬编码对齐。
    猜你喜欢
    • 2016-08-23
    • 1970-01-01
    • 1970-01-01
    • 2012-08-02
    • 1970-01-01
    • 2015-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多