C# ListView刷新工作不正常
编辑:我已经弄明白了为什么文本被画成粗体。因为对第一列调用了两次OnDrawSubItem。有人知道为什么吗C# ListView刷新工作不正常,c#,winforms,C#,Winforms,编辑:我已经弄明白了为什么文本被画成粗体。因为对第一列调用了两次OnDrawSubItem。有人知道为什么吗 我已经创建了一个从ListView类继承的自定义控件。我已重写OnDrawSubItem和OnDrawItem方法,如下所示: protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e) { Rectangle rowBounds = e.SubItem.Bounds;
我已经创建了一个从ListView类继承的自定义控件。我已重写OnDrawSubItem和OnDrawItem方法,如下所示:
protected override void OnDrawSubItem(DrawListViewSubItemEventArgs e)
{
Rectangle rowBounds = e.SubItem.Bounds;
Rectangle labelBounds = e.Item.GetBounds(ItemBoundsPortion.Label);
Rectangle bounds = new Rectangle(rowBounds.Left + 5, rowBounds.Top + 2, labelBounds.Width - 5, rowBounds.Height + 2);
if (e.Item.Selected)
e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.White, bounds);
else
e.Graphics.DrawString(e.SubItem.Text, Font, Brushes.Black, bounds);
}
protected override void OnDrawItem(DrawListViewItemEventArgs e)
{
e.DrawBackground();
if (e.Item.Selected)
{
Rectangle rowBounds = e.Bounds;
Rectangle bounds = new Rectangle(0, rowBounds.Top, rowBounds.Width, rowBounds.Height);
e.Graphics.FillRectangle(Brushes.Gray, bounds);
}
}
但有些东西不能正常工作。当我向ListView添加一些项目时,文本有点厚。listview被放置在选项卡中。当我切换到另一个选项卡并使用listview返回该选项卡时,文本似乎很好。因此,我尝试这样做,并尝试在项目添加操作结束时添加listView.Refresh()
,但没有成功:
//code 1
foreach(string s in new string[] { "item1", "item2", "item3", "item4", "item5" })
{
listView.Items.Add(s);
}
listView.Refresh();
输出为:
我还尝试在每次迭代时刷新,结果稍微好一点,但最后一个元素没有刷新:
//code 2
foreach(string s in new string[] { "item1", "item2", "item3", "item4", "item5" })
{
listView.Items.Add(s);
listView.Refresh();
}
输出:
切换选项卡时,所有文本都是它们应该显示的内容
我的两个问题是:
另外,也许值得一提的是,如果我添加第二列,第二列的渲染效果会很好。您在使用DrawString之前是否尝试过调用?这可能会删除厚文本。当我单击某个内容时,它会删除文本。