覆盖WinForm ListView控件上的Drawitem事件

Cha*_*adD 3 c# listview winforms

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

我想为列表视图做些人在这里为TreeView控件做的事情,即覆盖Drawingode事件:

当treeview没有焦点时,C#WinForms会突出显示treenode

我认为我需要将OwnerDraw属性设置为True覆盖DrawItem事件,但我不确定在这个事件中我需要做什么.... :-)

Dmi*_*try 8

你需要这样的东西:

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;
}
Run Code Online (Sandbox Code Playgroud)

编辑:改进View = View.DetailsFullRowSelect = true.
EDIT2:考虑了不同的列对齐类型,并添加了自动省略号标志.