请告诉我如何在桌面应用程序中将列表框的文本居中对齐。我在Visual Studio 2005中使用C#.Net。我正在使用Windows窗体。
qlzsbp2j1#
您可以将ListBox的DrawMode属性设置为DrawMode.OwnerDrawFixed,这使您可以控制每个项目的整个图形表示。例如:
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)); } }
8yparm6h2#
在WPF中,您将使用Control.HorizontalContentAligment属性:
<ListBox Name="lstSample" HorizontalContentAlignment="Center" <ListBoxItem>Item 1</ListBoxItem> <ListBoxItem>Item 2</ListBoxItem> <ListBoxItem>Item 3</ListBoxItem> </ListBox>
在Windows窗体中,你必须通过处理DrawItem事件来自己绘制ListBox的内容。
j1dl9f463#
使用TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;
TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;
listBox1.DrawMode = DrawMode.OwnerDrawFixed; listBox1.DrawItem += new DrawItemEventHandler(listBox1_OnDrawItem); private void listBox1_OnDrawItem(object sender,DrawItemEventArgs e) { TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter; if (e.Index >= 0) { e.DrawBackground(); var textRect = e.Bounds; string itemText = DesignMode ? "Custom ListBox" : Items[e.Index].ToString(); TextRenderer.DrawText(e.Graphics, itemText, e.Font, textRect, e.ForeColor, flags); e.DrawFocusRectangle(); } }
3条答案
按热度按时间qlzsbp2j1#
您可以将ListBox的
DrawMode
属性设置为DrawMode.OwnerDrawFixed
,这使您可以控制每个项目的整个图形表示。例如:8yparm6h2#
在WPF中,您将使用Control.HorizontalContentAligment属性:
在Windows窗体中,你必须通过处理DrawItem事件来自己绘制ListBox的内容。
j1dl9f463#
使用
TextFormatFlags flags = TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter;