【问题标题】:How to make Listbox's texts center aligned in desktop application using c#.net如何使用 c#.net 在桌面应用程序中使列表框文本中心对齐
【发布时间】:2011-02-25 23:09:51
【问题描述】:

请告诉我如何在桌面应用程序中将中心与列表框的文本对齐。
我在 Visual Studio 2005 中使用 C#.Net。

我正在使用 Windows 窗体。

【问题讨论】:

    标签: c# winforms listbox alignment


    【解决方案1】:

    您可以将 ListBox 的 DrawMode 属性设置为 DrawMode.OwnerDrawFixed,这样您就可以控制每个项目的整个图形表示。例如:

    ListBox listBox = new ListBox();
    listBox.DrawMode = DrawMode.OwnerDrawFixed;
    listBox.DrawItem += new DrawItemEventHandler(listBox_DrawItem);
    
        void listBox_DrawItem(object sender, DrawItemEventArgs e)
        {
            ListBox list = (ListBox)sender;
            if (e.Index > -1)
            {
                object item = list.Items[e.Index];
                e.DrawBackground();
                e.DrawFocusRectangle();
                Brush brush = new SolidBrush(e.ForeColor);
                SizeF size = e.Graphics.MeasureString(item.ToString(), e.Font);
                e.Graphics.DrawString(item.ToString(), e.Font, brush, e.Bounds.Left + (e.Bounds.Width / 2 - size.Width / 2), e.Bounds.Top + (e.Bounds.Height / 2 - size.Height / 2)); 
            }
        }
    

    【讨论】:

    • 是的。但是请使用 TextRenderer.DrawText。
    【解决方案2】:

    在 WPF 中,您将使用 Control.HorizontalContentAligment 属性:

    <ListBox Name="lstSample" 
             HorizontalContentAlignment="Center"
        <ListBoxItem>Item 1</ListBoxItem>
        <ListBoxItem>Item 2</ListBoxItem>
        <ListBoxItem>Item 3</ListBoxItem>
    </ListBox>
    

    在 Windows 窗体中,您必须自己通过处理 DrawItem 事件来绘制 ListBox 的内容。这是example on how to do it

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-15
      相关资源
      最近更新 更多