能否将ListBox的单个列设置为居中对齐格式?
ListBox单列居中对齐的实现方法
当然可行,不同UI框架下的实现方式略有不同,具体如下:
WinForms 实现方式
如果是WinForms的ListBox,默认单列显示时,需要通过自定义绘制来实现居中:
- 把ListBox的
DrawMode属性设置为OwnerDrawFixed - 绑定
DrawItem事件,在事件处理方法中手动绘制居中的文本
代码示例:
private void listBox1_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); if (e.Index >= 0) { TextRenderer.DrawText(e.Graphics, listBox1.Items[e.Index].ToString(), e.Font, e.Bounds, e.ForeColor, TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter); } e.DrawFocusRectangle(); }
WPF 实现方式
WPF的ListBox更灵活,有两种常用方式:
- 方式一:自定义
ItemTemplate,用居中的TextBlock承载内容
<ListBox x:Name="listBox"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding}" HorizontalAlignment="Center"/> </DataTemplate> </ListBox.ItemTemplate> </ListBox>
- 方式二:修改
ItemContainerStyle,设置内容的水平对齐方式
<ListBox x:Name="listBox"> <ListBox.ItemContainerStyle> <Style TargetType="ListBoxItem"> <Setter Property="HorizontalContentAlignment" Value="Center"/> </Style> </ListBox.ItemContainerStyle> </ListBox>
内容的提问来源于stack exchange,提问作者William Cezar
相关产品推荐
相关产品推荐

