简体   繁体   English

CodeGo.net>如何与对象在另一种方法进行交互?

[英]c# - How to interact with object in another method?

I'm populating a self-made Windows Explorer using TreeView & ListView ; 我正在使用TreeView和ListView填充一个自制的Windows资源管理器 and I'm currently working on Creating new Folder. 并且我目前正在创建新文件夹。 What I want to do is when I press the "New Folder" button, a new listView Item would be added with the name "New folder". 我想做的是,当我按下“ New Folder”按钮时,将添加一个名为“ New folder”的新listView项。 After that, let users type in the name of the folder by using BeginEdit() method. 之后,让用户使用BeginEdit()方法输入文件夹的名称。

private void buttonNewFolder_Click(object sender, EventArgs e)
        {
            ListViewItem newFolder = listView1.Items.Add("New folder", 1);
            newFolder.BeginEdit();
        }


private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            Directory.CreateDirectory("C:\"+e.Label); //for example
            // Now how can I change some properties of the "newFolder" listView Item in the above methods (buttonNewFolder_Click) ?
        }

In listView1_AfterLabelEdit method, i use Directory.CreateDirectory("C:\\"+e.Label); listView1_AfterLabelEdit方法中,我使用Directory.CreateDirectory("C:\\"+e.Label); statement to create a new folder. 创建新文件夹的语句。 But now, i want to change some properties of the above "newFolder" ListViewItem (for example Tag, ToolTipItem.. - for another use). 但是现在,我想更改上述“ newFolder” ListViewItem的某些属性(例如Tag,ToolTipItem ..-用于其他用途)。 How can I interact with that ListView Item in buttonNewFolder_Click method ??? 如何在buttonNewFolder_Click方法中与该ListView项交互? Really really hope you guys can help ! 真的很希望你们能提供帮助! Thanks sooo much in advanced ! 非常感谢高级!

newFolder lives within the scope of buttonNewFolder_Click only. newFolder仅在buttonNewFolder_Click的范围内。 Literally move it outside the method to make it more 'globally' accessible: 从字面上将其移到方法之外,以使其更“可全局”访问:

ListViewItem newFolder;

private void buttonNewFolder_Click(object sender, EventArgs e)
        {
            newFolder = listView1.Items.Add("New folder", 1);
            newFolder.BeginEdit();
        }


private void listView1_AfterLabelEdit(object sender, LabelEditEventArgs e)
        {
            Directory.CreateDirectory("C:\"+e.Label); //for example
            //You now have access to newFolder here
        }

IMPORTANT: It's a real possibiliy that (depending on the order in which these events are fired/methods are called) newFolde r may be null. 重要提示:(取决于触发这些事件/调用方法的顺序) newFolde r可能为空,这确实是可能的。 Do your necessary checks, code as defensively as possible when accessing newFolder in either method, now that it can be accessed at many more points throughout the code. 现在,无论哪种方法都可以在访问newFolder时进行必要的检查,并尽可能防御性地编写代码,因为现在可以在整个代码中的更多地方访问它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM