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

751 views Asked by At

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?

2

There are 2 answers

0
Kyle McClellan On BEST ANSWER

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;
1
Aaron Marten On

Check out this FAQ article which explains how to register for ProjectItems events (including ItemDeleted).