这是一个非常简单的问题,但我认为事实证明它比听起来要困难得多
当焦点离开 ListView 时,我想保留 ListView 项目的选择,目前我已将 hideselection
属性设置为 false,这很好......它确实导致 ListView 失去焦点后留下非常浅的灰色选择,所以我的问题是,如何正确显示该项目仍然处于选中状态,以便用户能够识别出这一点,例如更改行文本颜色或背景颜色?或者只是保持突出显示,因为第一次选择时整行变成蓝色?
我查看了 intelisense,但似乎找不到行、项目或所选项目的单独颜色属性的任何内容?
它必须存在,因为所选项目有自己的背景颜色,我可以在哪里更改它?
哦, ListView 确实需要保留在详细信息 View 中,这意味着我无法使用我在谷歌搜索时找到的唯一方法
谢谢
最佳答案
这是一个ListView的解决方案,它不允许多选并且 没有图像(例如复选框)。
- 为 ListView 设置事件处理程序(在本示例中名为 listView1):
- 绘图项目
- 离开(当 ListView 失去焦点时调用)
- 声明一个全局 int 变量(即包含 ListView 的 Form 的成员,
在此示例中,它被命名为gListView1LostFocusItem)并为其分配值-1
- int gListView1LostFocusItem = -1;
按如下方式实现事件处理程序:
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 控件进行子类化,以便您 可以将 protected 属性 DoubleBuffered 更改为 true。
public class ListViewEx : ListView
{
public ListViewEx() : base()
{
this.DoubleBuffered = true;
}
}
我创建了上述类的类库,以便可以将其添加到工具箱中。
关于c# - ListView 突出显示所选内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10915643/