ListView.OwnerDraw = true
),然后处理 ListView.DrawSubItem
事件来实现。如果需要,可以使用默认值处理 ListView.DrawColumnHeader
事件。Graphics.DrawText
,你会注意到差异。TextFormatFlags flags = TextFormatFlags.LeftAndRightPadding |
TextFormatFlags.VerticalCenter;
private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
{
var lv = sender as ListView;
var subItem = lv.HitTest(lv.PointToClient(MousePosition)).SubItem;
if (subItem != null && e.SubItem == subItem) {
using (var brush = new SolidBrush(SystemColors.Highlight)) {
e.Graphics.FillRectangle(brush, e.SubItem.Bounds);
}
TextRenderer.DrawText(e.Graphics, e.SubItem.Text, e.SubItem.Font,
e.Bounds, SystemColors.HighlightText, flags);
}
else {
e.DrawDefault = true;
}
}
private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)
=> e.DrawDefault = true;
// Invalidate on a mouse interaction, otherwise the ListView doesn't redraw the SubItem
private void listView1_MouseUp(object sender, MouseEventArgs e)
=> (sender as ListView).Invalidate();
MouseDown
事件),您可以更改子项的颜色并保存先前的状态(仅在此处使用颜色)。最好保存状态,因为每个子项都可以有自己的设置,因此您不能仅将其恢复为父ListViewItem或ListView值。UseItemStyleForSubItems = false
}},否则将忽略颜色设置。 false
,否则没有意义:)(ListViewSubItem,Color [])
中。private (ListViewItem.ListViewSubItem Item, Color[] colors)? previousItem = null;
private void listView1_MouseDown(object sender, MouseEventArgs e)
{
var lv = sender as ListView;
var subItem = lv.HitTest(e.Location).SubItem;
if (previousItem.HasValue) {
// If an Item's Colors have been changed, restore the state
// It removes the selection if you click in an empty area
previousItem.Value.Item.BackColor = previousItem.Value.colors[0];
previousItem.Value.Item.ForeColor = previousItem.Value.colors[1];
lv.Invalidate(previousItem.Value.Item.Bounds);
}
if (subItem != null) {
// Save the SubItem's colors state
previousItem = (subItem, new[] { subItem.BackColor, subItem.ForeColor });
// Set new Colors. Here, using the default highlight colors
subItem.BackColor = SystemColors.Highlight;
subItem.ForeColor = SystemColors.HighlightText;
lv.Invalidate(subItem.Bounds);
}
}
这是这个东西的工作原理:
关于项目/子项目索引,正如问题中所提到的:
当您使用 ListView.HitTest 检索单击的 ListViewItem
/SubItem
时。
var hitTest = lv.HitTest(e.Location);
那么ListViewItem的索引当然是:
var itemIndex = hitTest.Item.Index;
而 SubItem.Index
是:
var subItemIndex = hitTest.Item.SubItems.IndexOf(hitTest.SubItem);
dataGridView1.DataSource = list;
一样容易,或者您要在这里做的就像dataGridView1.SelectionMode = DataGridViewSelectionMode.CellSelect;
一样简单。我认为最好将其视为未来应用程序的选项 :) - Reza Aghaei