Fenêtres d'outils

Créez une fenêtre d’outil ancrable avec une interface utilisateur liée aux données à l’aide de Remote UI et du VisualStudio.Extensibility SDK.

Note

Ce guide utilise le Kit de développement logiciel (SDK) VisualStudio.Extensibility . Consultez Choisir le modèle d’extensibilité approprié pour la comparaison de modèles.

Exemple complet

Implémentation complète :

La définition de la fenêtre d'outil :

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace ToolWindowSample;

using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.Extensibility.Commands;
using Microsoft.VisualStudio.Extensibility.ToolWindows;
using Microsoft.VisualStudio.RpcContracts.RemoteUI;

/// <summary>
/// A sample tool window.
/// </summary>
[VisualStudioContribution]
public class MyToolWindow : ToolWindow
{
    private object? dataContext;

    /// <summary>
    /// Initializes a new instance of the <see cref="MyToolWindow" /> class.
    /// </summary>
    public MyToolWindow()
    {
        this.Title = "My Tool Window";
    }

    /// <inheritdoc />
    public override ToolWindowConfiguration ToolWindowConfiguration => new()
    {
        Placement = ToolWindowPlacement.DocumentWell,
        Toolbar = new ToolWindowToolbar(Toolbar),
    };

    [VisualStudioContribution]
    private static ToolbarConfiguration Toolbar => new("%ToolWindowSample.MyToolWindow.Toolbar.DisplayName%")
    {
        Children = [ToolbarChild.Command<MyToolbarCommand>()],
    };

    /// <inheritdoc />
    public override Task InitializeAsync(CancellationToken cancellationToken)
    {
        this.dataContext = new MyToolWindowData(this.Extensibility);

        return Task.CompletedTask;
    }

    /// <inheritdoc />
    public override Task<IRemoteUserControl> GetContentAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult<IRemoteUserControl>(new MyToolWindowControl(this.dataContext));
    }
}

La commande permettant d’ouvrir la fenêtre d'outil :

// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace ToolWindowSample;

using System.Threading;
using System.Threading.Tasks;
using Microsoft.VisualStudio.Extensibility;
using Microsoft.VisualStudio.Extensibility.Commands;

/// <summary>
/// A sample command for showing a tool window.
/// </summary>
[VisualStudioContribution]
public class MyToolWindowCommand : Command
{
    /// <inheritdoc />
    public override CommandConfiguration CommandConfiguration => new("%ToolWindowSample.MyToolWindowCommand.DisplayName%")
    {
        Placements = [CommandPlacement.KnownPlacements.ToolsMenu],
        Icon = new(ImageMoniker.KnownValues.ToolWindow, IconSettings.IconAndText),
    };

    /// <inheritdoc />
    public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken cancellationToken)
    {
        await this.Extensibility.Shell().ShowToolWindowAsync<MyToolWindow>(activate: true, cancellationToken);
    }
}

Tip

Consultez l'exemple complet fonctionnel : ToolWindowSample ↗

Concepts connexes :Interface utilisateur distante — le modèle de liaison de données utilisé pour le contenu de la fenêtre d’outil, Contributions et configurations — comment les contributions de fenêtre d’outil sont déclarées

Comprenez l’exemple

Étape 1 : Définir la classe de fenêtre d’outils

Étendez ToolWindow et marquez-le avec [VisualStudioContribution]:

[VisualStudioContribution]
internal class MyToolWindow : ToolWindow
{
    private MyDataModel? dataModel;

    public MyToolWindow(VisualStudioExtensibility extensibility)
        : base(extensibility)
    {
        Title = "My Tool Window";
    }

    public override ToolWindowConfiguration ToolWindowConfiguration => new()
    {
        Placement = ToolWindowPlacement.DocumentWell,
        AllowAutoCreation = true,
    };

    public override async Task InitializeAsync(CancellationToken cancellationToken)
    {
        dataModel = new MyDataModel();
        await dataModel.LoadAsync(cancellationToken);
    }

    public override Task<IRemoteUserControl> GetContentAsync(CancellationToken cancellationToken)
    {
        return Task.FromResult<IRemoteUserControl>(new MyToolWindowControl(dataModel!));
    }
}

Étape 2 : Créer le modèle de données

Utilisez [DataContract] avec NotifyPropertyChangedObject et [DataMember] pour la liaison de données de Remote UI :

[DataContract]
internal class MyDataModel : NotifyPropertyChangedObject
{
    private string message = "Hello from the tool window!";

    [DataMember]
    public string Message
    {
        get => message;
        set => SetProperty(ref message, value);
    }

    public async Task LoadAsync(CancellationToken cancellationToken)
    {
        // Load data asynchronously
    }
}

Étape 3 : Créer le contrôle Remote UI

Ajoutez une classe RemoteUserControl et un modèle de données XAML correspondant.

MyToolWindowControl.cs:

internal class MyToolWindowControl : RemoteUserControl
{
    public MyToolWindowControl(MyDataModel dataModel)
        : base(dataContext: dataModel)
    {
    }
}

MyToolWindowControl.xaml : définissez l’action de génération sur EmbeddedResource (et non page) :

<DataTemplate xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
              xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
              xmlns:vs="http://schemas.microsoft.com/visualstudio/extensibility/2022/xaml">
    <StackPanel Margin="10">
        <TextBlock Text="{Binding Message}" FontSize="14" />
    </StackPanel>
</DataTemplate>

Important

Le fichier XAML doit utiliser l’action de génération EmbeddedResource. Le définir sur Page entraînera le rendu d’une fenêtre d’outil vide.

Étape 4 : Ajouter une commande pour afficher la fenêtre de l’outil

[VisualStudioContribution]
internal class ShowMyToolWindowCommand : Command
{
    public ShowMyToolWindowCommand(VisualStudioExtensibility extensibility)
        : base(extensibility)
    {
    }

    public override CommandConfiguration CommandConfiguration => new("My Tool Window")
    {
        Placements = [CommandPlacement.KnownPlacements.ViewOtherWindowsMenu],
        Icon = new(ImageMoniker.KnownValues.ToolWindow, IconSettings.IconAndText),
    };

    public override async Task ExecuteCommandAsync(IClientContext context, CancellationToken cancellationToken)
    {
        await Extensibility.Shell().ShowToolWindowAsync<MyToolWindow>(activate: true, cancellationToken);
    }
}

Étape 5 (facultatif) : Ajouter une barre d’outils

Définissez une barre d’outils et faites-y référence dans ToolWindowConfiguration :

[VisualStudioContribution]
public static ToolbarConfiguration MyToolbar => new("%MyToolbar.DisplayName%")
{
    Children = [
        ToolbarChild.Command<RefreshCommand>(),
        ToolbarChild.Separator,
        ToolbarChild.Command<ClearCommand>(),
    ],
};

public override ToolWindowConfiguration ToolWindowConfiguration => new()
{
    Placement = ToolWindowPlacement.DocumentWell,
    Toolbar = new(MyToolbar),
};

Tips

✅ DO

  • Marquez les fichiers XAML avec l’action de génération EmbeddedResource (et non Page).
  • Utilisez [DataContract] et [DataMember] sur les propriétés ViewModel pour l’interface utilisateur distante.
  • Utiliser NotifyPropertyChangedObject comme base pour les modèles de données.
  • Initialiser des données dans InitializeAsync(), créer l’interface utilisateur dans GetContentAsync().
  • Utilisez ShowToolWindowAsync<T>(activate: true) pour afficher à partir des commandes.

❌ À NE PAS FAIRE

  • N'utilisez pas WPF directement : Remote UI est requis pour les extensions hors processus.
  • Ne définissez pas l’action de génération XAML sur Page (la fenêtre outil ne s’affiche pas).
  • Ne créez pas de ressources coûteuses dans le constructeur : utilisez InitializeAsync.

🔧 Résolution des problèmes

Symptôme Réparer
La fenêtre d'outil est vide Vérifier que l’action de génération XAML est EmbeddedResource
La liaison de données ne se met pas à jour Vérifier que ViewModel hérite de NotifyPropertyChangedObject et que les propriétés ont [DataMember]
La fenêtre n’apparaît pas Vérifiez que les appels de commande ShowToolWindowAsync sont corrects
Barre d’outils non affichée Vérifier que l’option ToolWindowConfiguration.Toolbar est définie

Étapes suivantes