为什么我没有listView1上的属性项?

时间:2014-12-11 10:51:52

标签: c# .net winforms

在此方法中将文件添加到listView1时,我确实拥有属性Items。

private void AddFiles(string strPath)
    {       
        listView1.BeginUpdate();

        listView1.Items.Clear();
        iFiles = 0;
        try
        {
            DirectoryInfo di = new DirectoryInfo(strPath + "\\");           
            FileInfo[] theFiles = di.GetFiles();            
            foreach(FileInfo theFile in theFiles)
            {
                iFiles++;
                ListViewItem lvItem = new ListViewItem(theFile.Name);
                lvItem.SubItems.Add(theFile.Length.ToString());
                lvItem.SubItems.Add(theFile.LastWriteTime.ToShortDateString());
                lvItem.SubItems.Add(theFile.LastWriteTime.ToShortTimeString());
                listView1.Items.Add(lvItem);                                    
            }
        }
        catch(Exception Exc)    {   statusBar1.Text = Exc.ToString();   }

        listView1.EndUpdate();      
    }

但是现在我想添加属性,所以当我正在鼠标右键单击文件时它会显示一个上下文菜单:

private void listView1_MouseUp(object sender, MouseEventArgs e)
    {
        if (e.Button == MouseButtons.Right)
        {
            int index = listView1.IndexFromPoint(e.Location);
            if (index != ListBox.NoMatches)
            {
                listJobs.SelectedIndex = index;

                Job job = (Job)listJobs.Items[index];

                ContextMenu cm = new ContextMenu();


                AddMenuItem(cm, "Run", QueueForRun, job).Enabled = !job.Pending;
                AddMenuItem(cm, "Cancel run", CancelQueueForRun, job).Enabled = (job.State == JobState.Pending || job.State == JobState.Running);
                AddMenuItem(cm, "Open folder", OpenFolder, job);

                cm.Show(listJobs, e.Location);
            }
        }
    }

这次我没有IndexFromPoint,也没有Items

1 个答案:

答案 0 :(得分:4)

由于IndexFromPoint()ListBox方法,ListView没有。在ListView中,有GetItemAt()方法可以获得相同的结果。

var item = listView.GetItemAt(e.Location.X, e.Location.Y);
if (item != null) {
    listJobs.SelectedIndex = item.Index; // Assuming listJobs is a ListBox
}

编辑:根据您的评论,如果listJobs还是ListView,那么它还没有SelectedIndex但它有SelectedIndices,只需:

listJobs.SelectedIndices.Clear();
listJobs.SelectedIndices.Add(item.Index);

首先要清除列表,因为默认情况下,MultiSelecttrue,您可以选择多个项目。