【问题标题】:ListView OwnerDraw with AllowColumnReorder don't work correct带有 AllowColumnReorder 的 ListView OwnerDraw 无法正常工作
【发布时间】:2015-03-06 15:48:16
【问题描述】:

我正在绘制自定义 ListView,将 OwnerDraw 属性设置为“true”。 listview 也有 AllowColumnReorder 'true' 属性。

private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
    e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.Black, e.Bounds);
}

这工作正常:

但如果我移动第一列,则会出现绘图问题 - 前两列的数据被绘制在第一列,而被移动列的数据根本没有被绘制:

发生这种情况是因为 e.Bounds 的两个不同列的值相等。我该怎么做才能获得正确的 e.Bounds 值。

【问题讨论】:

    标签: c# .net listview


    【解决方案1】:

    是的,这是 ListView 类中的一个错误。它的私人GetItemRectOrEmpty() method 是borken。编写为错误解决方法,内部错误号 VSWhidbey #163674。修复一个错误导致另一个错误是一个非常传统的编程事故,大男孩们也会这样做:) 当它向 Windows 询问项目矩形时,通过 e.Bounds 属性传递给你,它会失败并询问 ItemBoundsPortion.Entire。这是完整的 ListViewItem 矩形,包括子项。

    幸运的是,解决方法很简单,您可以自己使用 ItemBoundsPortion.ItemOnly:

    private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e) {
        var bounds = e.Bounds;
        if (e.ColumnIndex == 0) {
            bounds = listView1.GetItemRect(e.ItemIndex, ItemBoundsPortion.ItemOnly);
        }
        e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.Black, bounds);
    }
    

    【讨论】:

    • 它没有帮助。 GetItemRect 方法返回完整的项目矩形。但是当我移动此列时, column_0 的 DisplayIndex 属性没有变为 0。如何获取当前子项的矩形?
    • 我对此进行了非常彻底的测试,工作正常。你正在做一些我不知道的事情。否则,期望有人从屏幕截图中修复错误的责任。
    【解决方案2】:

    感谢 Hans Passant 提供信息。我使用下一个代码修复了这个错误:

    private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            Rectangle bounds = e.Bounds;
            if (e.ColumnIndex == 0 && listView1.Columns[0].DisplayIndex != 0)
            {
                bounds = GetFirstColumnCorrectRectangle(e.Item);
            }
            e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.Black, bounds);
        }
    
        private Rectangle GetFirstColumnCorrectRectangle(ListViewItem item)
        {
            int i;
            for (i = 0; i < listView1.Columns.Count; i++)
                if (listView1.Columns[i].DisplayIndex == listView1.Columns[0].DisplayIndex - 1)
                    break;
            return new Rectangle(item.SubItems[i].Bounds.Right, item.SubItems[i].Bounds.Y, listView1.Columns[0].Width, item.SubItems[i].Bounds.Height);
        }
    

    【讨论】:

      猜你喜欢
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多