简体   繁体   中英

How can I listen for the deletion of a ProjectItem via DTE?

I've got a designer that relies on the existence of other solution items. If one of those items is deleted the designer crashes and you have to edit as XML to fix. Not exactly user friendly.

I do, however, have the DTE object representing the instance of Visual Studio, as well as the ProjectItems I am dependent on.

Is it possible to, somewhere in the depths of the DTE, register a listener for the deletion of that ProjectItem? And, if so, How would I do it?

It looks like the culprit here is garbage collection. I found the following two event sets behaved identically.

Events2 events2 = dte.Events as Events2;
if (events2 != null)
{
    this.projectItemsEvents = events2.ProjectItemsEvents;
    this.projectItemsEvents.ItemAdded += this.ProjectItemsEvents_ItemAdded;
    this.projectItemsEvents.ItemRemoved += this.ProjectItemsEvents_ItemRemoved;
    this.projectItemsEvents.ItemRenamed += this.ProjectItemsEvents_ItemRenamed;
}

this.csharpProjectItemsEvents =
    dte.Events.GetObject("CSharpProjectItemsEvents") as ProjectItemsEvents;
if (this.csharpProjectItemsEvents != null)
{
    this.csharpProjectItemsEvents.ItemAdded += this.CSharpProjectItemsEvents_ItemAdded;
    this.csharpProjectItemsEvents.ItemRemoved += this.CSharpProjectItemsEvents_ItemRemoved;
    this.csharpProjectItemsEvents.ItemRenamed += this.CSharpProjectItemsEvents_ItemRenamed;
}

The key to both was making sure to keep a reference to the events object in the subscriber. Once I added the reference, they behaved like I expected.

private ProjectItemsEvents projectItemsEvents;
private ProjectItemsEvents csharpProjectItemsEvents;

查看此FAQ文章该文章解释了如何注册ProjectItems事件(包括ItemDeleted)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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