Question

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?

Was it helpful?

Solution

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;

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top