List view Highlight selected
这是一个很简单的问题,但我认为它比听起来要困难得多
我想在焦点离开列表视图时保留对列表视图项的选择,目前我已将
我通过 intelisense 进行了查看,但似乎无法为行或项目或所选项目的单个颜色属性找到任何内容?
它必须存在,因为所选项目有自己的背景颜色,我在哪里可以更改它?
哦,列表视图确实需要保留在详细信息视图中,这意味着我不能使用我在谷歌搜索时能够找到的唯一方法
谢谢
这里是 ListView 的解决方案,它不允许多选和
没有图像(例如复选框)。
- 绘图项
- 离开(ListView 失去焦点时调用)
在此示例中,它被命名为 gListView1LostFocusItem) 并将其赋值为 -1
- int gListView1LostFocusItem = -1;
按如下方式实现事件处理程序:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | private void listView1_Leave(object sender, EventArgs e) { // Set the global int variable (gListView1LostFocusItem) to // the index of the selected item that just lost focus gListView1LostFocusItem = listView1.FocusedItem.Index; } private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e) { // If this item is the selected item if (e.Item.Selected) { // If the selected item just lost the focus if (gListView1LostFocusItem == e.Item.Index) { // Set the colors to whatever you want (I would suggest // something less intense than the colors used for the // selected item when it has focus) e.Item.ForeColor = Color.Black; e.Item.BackColor = Color.LightBlue; // Indicate that this action does not need to be performed // again (until the next time the selected item loses focus) gListView1LostFocusItem = -1; } else if (listView1.Focused) // If the selected item has focus { // Set the colors to the normal colors for a selected item e.Item.ForeColor = SystemColors.HighlightText; e.Item.BackColor = SystemColors.Highlight; } } else { // Set the normal colors for items that are not selected e.Item.ForeColor = listView1.ForeColor; e.Item.BackColor = listView1.BackColor; } e.DrawBackground(); e.DrawText(); } |
注意:此解决方案可能会导致一些闪烁。解决此问题的方法是对 ListView 控件进行子类化,以便您
可以将受保护的属性 DoubleBuffered 更改为 true。
1 2 3 4 5 6 7 | public class ListViewEx : ListView { public ListViewEx() : base() { this.DoubleBuffered = true; } } |
我创建了上述类的类库,以便可以将其添加到工具箱中。
一个可能的解决方案可能是另一个问题的答案:
即使焦点在另一个控件上,如何更改列表视图选定行的背景颜色?