Certainly! Let's walk through the process of creating a Visual Studio 2022 extension that adds a "HELLO WORLD" IntelliSense completion in a .xaml document. This extension will suggest "HELLO WORLD" as an autocomplete option when you're editing XAML files in Visual Studio.
Overview
We'll create a Visual Studio Extension (VSIX) that implements an asynchronous completion source for XAML files. The extension will provide a custom completion item ("HELLO WORLD") that appears in the IntelliSense suggestions when editing .xaml files.
Prerequisites
- Visual Studio 2022 (Community, Professional, or Enterprise edition).
- Visual Studio SDK installed (can be installed via the Visual Studio Installer under "Individual Components" > "Visual Studio extension development").
Steps to Create the Extension
1. Create a New VSIX Project
-
Open Visual Studio 2022.
-
Create a new project:
- Go to File > New > Project.
- In the "Create a new project" window, search for "VSIX Project".
- Select "VSIX Project" and click Next.
-
Configure the project:
- Project Name: Enter a name for your project, e.g.,
XamlIntelliSenseExtension.
- Location: Choose a suitable location.
- Click Create.
2. Add Necessary NuGet Packages
We need to add packages that provide interfaces and classes for creating completion sources.
-
Manage NuGet Packages:
- Right-click on the project in the Solution Explorer.
- Select Manage NuGet Packages.
-
Install Microsoft.VisualStudio.SDK:
- Go to the Browse tab.
- Search for Microsoft.VisualStudio.SDK.
- Install the latest stable version.
3. Add References to Editor Assemblies
We'll need references to certain Visual Studio assemblies.
-
Add Reference:
- Right-click on References in the Solution Explorer.
- Choose Add Reference.
-
Select Assemblies:
4. Implement the Completion Source
We'll create a class that provides the custom completion item.
-
Add a new class:
- Right-click on the project.
- Select Add > Class.
- Name it
XamlCompletionSource.cs.
-
Implement the completion source:
- Replace the contents of
XamlCompletionSource.cs with the following code:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using System.Threading;
using System.Threading.Tasks;
namespace XamlIntelliSenseExtension
{
[Export(typeof(IAsyncCompletionSourceProvider))]
[Name("XAML Completion Source Provider")]
[ContentType("XAML")]
internal class XamlCompletionSourceProvider : IAsyncCompletionSourceProvider
{
public IAsyncCompletionSource GetOrCreate(ITextView textView)
{
return textView.Properties.GetOrCreateSingletonProperty(() => new XamlCompletionSource());
}
}
internal class XamlCompletionSource : IAsyncCompletionSource
{
private readonly CompletionItem _helloWorldItem;
public XamlCompletionSource()
{
_helloWorldItem = new CompletionItem("HELLO WORLD", this);
}
public Task<CompletionContext> GetCompletionContextAsync(
IAsyncCompletionSession session,
CompletionTrigger trigger,
SnapshotPoint triggerLocation,
CancellationToken cancellationToken)
{
var items = new List<CompletionItem> { _helloWorldItem };
return Task.FromResult(new CompletionContext(items));
}
public Task<object> GetDescriptionAsync(IAsyncCompletionSession session, CompletionItem item, CancellationToken cancellationToken)
{
return Task.FromResult<object>("Inserts 'HELLO WORLD' into the XAML file.");
}
public CompletionStartData InitializeCompletion(
CompletionTrigger trigger,
SnapshotPoint triggerLocation,
CancellationToken cancellationToken)
{
// Start completion when any letter is typed
if (char.IsLetter(trigger.Character) || trigger.Reason == CompletionTriggerReason.InvokeAndCommitIfUnique)
{
var completionSpan = triggerLocation.Snapshot.CreateTrackingSpan(
new Span(triggerLocation.Position, 0),
SpanTrackingMode.EdgeInclusive);
return new CompletionStartData(CompletionParticipation.ProvidesItems, completionSpan);
}
return CompletionStartData.DoesNotParticipateInCompletion;
}
public void Dispose()
{
// Dispose of any resources if necessary
}
}
}
Explanation:
- XamlCompletionSourceProvider: A MEF component that provides the
XamlCompletionSource for XAML content types.
- IAsyncCompletionSource: Interface that defines methods to provide completion items asynchronously.
- InitializeCompletion: Determines when completion should be triggered.
- GetCompletionContextAsync: Provides the list of completion items (in our case, just "HELLO WORLD").
- GetDescriptionAsync: Provides a description for the completion item.
5. Build and Test the Extension
Configure Debugging:
-
Set the VSIX project as the startup project:
- Right-click on the project in Solution Explorer.
- Choose Set as Startup Project.
-
Set debugging options:
-
Right-click on the project.
-
Select Properties.
-
Go to the Debug tab.
-
Ensure Start external program is set to the path of devenv.exe (Visual Studio executable). The default path is usually:
C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\devenv.exe
(Replace Community with Professional or Enterprise if applicable.)
Start Debugging:
-
Start debugging:
- Press F5 or go to Debug > Start Debugging.
-
Experimental Instance:
- An experimental instance of Visual Studio will launch. This is a sandboxed environment for testing extensions.
6. Test the IntelliSense Completion
-
Create a new WPF Application in the experimental instance:
- File > New > Project.
- Search for WPF App (.NET Core or .NET Framework).
- Create a new project.
-
Open MainWindow.xaml:
- In Solution Explorer, open MainWindow.xaml.
-
Trigger IntelliSense:
- Place the cursor within the
<Grid> element.
- Start typing any character to trigger IntelliSense.
- Alternatively, press Ctrl+Space.
-
Verify "HELLO WORLD" Suggestion:
- HELLO WORLD should appear in the IntelliSense completion list.
- Selecting it will insert "HELLO WORLD" into the XAML.
7. Build the Extension for Release (Optional)
If you wish to distribute the extension:
-
Set Configuration to Release:
- In Visual Studio, set the build configuration to Release.
-
Build the Solution:
- Go to Build > Build Solution.
-
Locate the VSIX File:
- The
.vsix file will be located in the bin\Release folder of your project.
- You can distribute this file or install it on your Visual Studio by double-clicking it.
Additional Information
Using Attributes Correctly
- The
[ContentType("XAML")] attribute ensures that the completion source is only active in XAML files.
- The
[Name("XAML Completion Source Provider")] attribute provides a friendly name for the MEF component.
References and Namespaces
Ensure that all necessary namespaces are included at the top of your class files:
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion;
using Microsoft.VisualStudio.Language.Intellisense.AsyncCompletion.Data;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Microsoft.VisualStudio.Utilities;
using System.Threading;
using System.Threading.Tasks;
Handling Trigger Characters
In InitializeCompletion, we check if the trigger character is a letter to decide whether to participate in completion. Adjust this logic based on when you want your completion to appear.
Disposal
Implement the Dispose method if your completion source holds onto any unmanaged resources.
Troubleshooting
IntelliSense Not Showing "HELLO WORLD"
- Check ContentType: Ensure the
[ContentType("XAML")] attribute is correctly specified.
- Rebuild the Project: Clean and rebuild the project to ensure changes are applied.
- Experimental Instance: Make sure you're testing in the experimental instance launched via debugging.
- No Errors: Check the Output window for any runtime errors that might prevent the extension from working.
Multiple IntelliSense Options
If "HELLO WORLD" is competing with other IntelliSense suggestions, you can adjust its Priority.
Conclusion
You've successfully created a Visual Studio extension that adds a custom IntelliSense completion to XAML files. This basic example can serve as a foundation for more complex extensions, such as context-aware suggestions, integration with external data sources, or other productivity enhancements.
Feel free to expand upon this example to meet your specific needs. If you have any questions or need further assistance, don't hesitate to ask!