【发布时间】:2011-02-25 23:09:51
【问题描述】:
请告诉我如何在桌面应用程序中将中心与列表框的文本对齐。
我在 Visual Studio 2005 中使用 C#.Net。
我正在使用 Windows 窗体。
【问题讨论】:
标签: c# winforms listbox alignment
请告诉我如何在桌面应用程序中将中心与列表框的文本对齐。
我在 Visual Studio 2005 中使用 C#.Net。
我正在使用 Windows 窗体。
【问题讨论】:
标签: c# winforms listbox alignment
您可以将 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));
}
}
【讨论】:
在 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。
【讨论】: