gpt4 book ai didi

c# - 覆盖 WinForm ListView 控件上的 Drawitem 事件

转载 作者:行者123 更新时间:2023-11-30 13:57:42 24 4
gpt4 key购买 nike

我希望我的 ListView 的选定项在失去焦点时保持清晰可见(它在 Windows 7 上是暗灰色)。我确实将 HideSelection 属性设置为 False。

我想为 ListView 做一些人在这里为 TreeView 控件所做的事情,即覆盖 Drawnode 事件:

C# WinForms highlight treenode when treeview doesnt have focus

我想我需要将 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.DetailsFullRowSelect = true
EDIT2:考虑了不同对齐类型的列,还添加了自动省略号标志。

关于c# - 覆盖 WinForm ListView 控件上的 Drawitem 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20012097/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com