C# 重写WinForm ListView控件上的Drawitem事件
我希望我的ListView所选的项目在焦点丢失时保持清晰可见(在Windows7上为暗灰色)。我确实将HideSelection属性设置为False 我想对列表视图执行某人在这里对TreeView控件所做的操作,即覆盖Drawnode事件:C# 重写WinForm ListView控件上的Drawitem事件,c#,winforms,listview,C#,Winforms,Listview,我希望我的ListView所选的项目在焦点丢失时保持清晰可见(在Windows7上为暗灰色)。我确实将HideSelection属性设置为False 我想对列表视图执行某人在这里对TreeView控件所做的操作,即覆盖Drawnode事件: 我假设我需要将OwnerDraw属性设置为True以覆盖DrawItem事件,但我不确定在此事件中需要执行什么操作…:-) 你需要这样的东西: private void listView1_DrawColumnHeader(object sender, D
我假设我需要将OwnerDraw属性设置为True以覆盖DrawItem事件,但我不确定在此事件中需要执行什么操作…:-) 你需要这样的东西:
private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
{
e.DrawDefault = true;
}
private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
const int TEXT_OFFSET = 1; // I don't know why the text is located at 1px to the right. Maybe it's only for me.
ListView listView = (ListView)sender;
// Check if e.Item is selected and the ListView has a focus.
if (!listView.Focused && e.Item.Selected)
{
Rectangle rowBounds = e.SubItem.Bounds;
Rectangle labelBounds = e.Item.GetBounds(ItemBoundsPortion.Label);
int leftMargin = labelBounds.Left - TEXT_OFFSET;
Rectangle bounds = new Rectangle(rowBounds.Left + leftMargin, rowBounds.Top, e.ColumnIndex == 0 ? labelBounds.Width : (rowBounds.Width - leftMargin - TEXT_OFFSET), rowBounds.Height);
TextFormatFlags align;
switch (listView.Columns[e.ColumnIndex].TextAlign)
{
case HorizontalAlignment.Right:
align = TextFormatFlags.Right;
break;
case HorizontalAlignment.Center:
align = TextFormatFlags.HorizontalCenter;
break;
default:
align = TextFormatFlags.Left;
break;
}
TextRenderer.DrawText(e.Graphics, e.SubItem.Text, listView.Font, bounds, SystemColors.HighlightText,
align | TextFormatFlags.SingleLine | TextFormatFlags.GlyphOverhangPadding | TextFormatFlags.VerticalCenter | TextFormatFlags.WordEllipsis);
}
else
e.DrawDefault = true;
}
private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)
{
ListView listView = (ListView)sender;
// Check if e.Item is selected and the ListView has a focus.
if (!listView.Focused && e.Item.Selected)
{
Rectangle rowBounds = e.Bounds;
int leftMargin = e.Item.GetBounds(ItemBoundsPortion.Label).Left;
Rectangle bounds = new Rectangle(leftMargin, rowBounds.Top, rowBounds.Width - leftMargin, rowBounds.Height);
e.Graphics.FillRectangle(SystemBrushes.Highlight, bounds);
}
else
e.DrawDefault = true;
}
编辑:改进了View=View.Details
和FullRowSelect=true
EDIT2:考虑了不同的列对齐类型,并添加了自动省略号标志。不幸的是,我的列表有多个列,当选择一行时,除了第一列之外,所有列的文本都会消失。我可以要求您也帮助实施抽签子项方法吗?我正在使用整行选择。我已根据您的需要更新了代码。现在,所有3个事件都已处理:
DrawItem
,DrawSubItem
,DrawColumnHeader
。除了一个小问题,即colimn不够大,无法显示全文,并且添加了省略号,它工作得非常好。fulkl列文本溢出到下一列。已修复。此外,还考虑了不同的列对齐类型。我已经解决了问题,这是基础Win32控件中的一个错误。当鼠标指针移动到行上时,在“详细信息”视图中每行发生一次DrawItem事件,但不伴随DrawSubItem事件。如果有人面临同样的问题,解决方案如下: