Пошаговое руководство: Создание глиф полей
Можно настраивать внешний вид редактора полей с помощью расширений специализированного редактора. В этом пошаговом руководстве помещает пользовательский глиф в поле индикаторов при машинное слово "todo" отображается в комментарий кода.
Обязательные компоненты
Чтобы выполнить это пошаговое руководство, необходимо устанавливать SDK для Visual Studio 2010.
Примечание
Дополнительные сведения о пакете SDK для Visual Studio см. в разделе интеграция SDK Visual Studio.Чтобы узнать, как загрузить пакет SDK для Visual Studio см. в разделе Центр разработчиков расширяемости Visual Studio на веб-сайте MSDN.
Создание управляемой расширяемости проекта .NET Framework (платформа MEF)
Создание проекта MEF
Создайте проект Visual c# или Visual Basic классификатора редактор. Назовите решение TodoGlyphTest.
Откройте файл Source.extension.vsixmanifest в редакторе манифеста VSIX.
Убедитесь, что Content заголовок содержит тип содержимого и компонент MEF Path имеет значение TodoGlyphTest.dll.
Сохранить и закрыть Source.extension.vsixmanifest.
Удалите существующие файлы классов.
Указание глиф
Укажите глиф путем реализации IGlyphFactory интерфейс.
Указать глиф
Добавьте файл классов и назовите его TodoGlyphFactory.
Добавьте следующие ввозы.
Imports System.ComponentModel.Composition Imports System.Windows Imports System.Windows.Shapes Imports System.Windows.Media Imports System.Windows.Controls Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Formatting Imports Microsoft.VisualStudio.Text.Tagging Imports Microsoft.VisualStudio.Utilities
using System.ComponentModel.Composition; using System.Windows; using System.Windows.Shapes; using System.Windows.Media; using System.Windows.Controls; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Formatting; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Utilities;
Добавьте в проект класс TodoGlyphFactory, реализующий IGlyphFactory.
Friend Class TodoGlyphFactory Implements IGlyphFactory
internal class TodoGlyphFactory : IGlyphFactory
Добавьте закрытое поле, который задает размеры глифа.
Const m_glyphSize As Double = 16.0
const double m_glyphSize = 16.0;
Реализуйте GenerateGlyph задавая элемент пользовательского интерфейса глифов (пользовательского интерфейса). TodoTag определяет далее в этом пошаговом руководстве.
Public Function GenerateGlyph(ByVal line As IWpfTextViewLine, ByVal tag As IGlyphTag) As System.Windows.UIElement Implements IGlyphFactory.GenerateGlyph ' Ensure we can draw a glyph for this marker. If tag Is Nothing OrElse Not (TypeOf tag Is TodoTag) Then Return Nothing End If Dim ellipse As Ellipse = New Ellipse() ellipse.Fill = Brushes.LightBlue ellipse.StrokeThickness = 2 ellipse.Stroke = Brushes.DarkBlue ellipse.Height = m_glyphSize ellipse.Width = m_glyphSize Return ellipse End Function
public UIElement GenerateGlyph(IWpfTextViewLine line, IGlyphTag tag) { // Ensure we can draw a glyph for this marker. if (tag == null || !(tag is TodoTag)) { return null; } System.Windows.Shapes.Ellipse ellipse = new Ellipse(); ellipse.Fill = Brushes.LightBlue; ellipse.StrokeThickness = 2; ellipse.Stroke = Brushes.DarkBlue; ellipse.Height = m_glyphSize; ellipse.Width = m_glyphSize; return ellipse; }
Добавьте в проект класс TodoGlyphFactoryProvider, реализующий IGlyphFactoryProvider. Экспортировать этот класс с a NameAttribute "TodoGlyph" OrderAttribute после VsTextMarker, a ContentTypeAttribute "кода" и " a " TagTypeAttribute TodoTag.
<Export(GetType(IGlyphFactoryProvider)), Name("TodoGlyph"), Order(After:="VsTextMarker"), ContentType("code"), TagType(GetType(TodoTag))> Friend NotInheritable Class TodoGlyphFactoryProvider Implements IGlyphFactoryProvider
[Export(typeof(IGlyphFactoryProvider))] [Name("TodoGlyph")] [Order(After = "VsTextMarker")] [ContentType("code")] [TagType(typeof(TodoTag))] internal sealed class TodoGlyphFactoryProvider : IGlyphFactoryProvider
Реализуйте GetGlyphFactory метод путем создания экземпляра TodoGlyphFactory.
Public Function GetGlyphFactory(ByVal view As IWpfTextView, ByVal margin As IWpfTextViewMargin) As IGlyphFactory Implements IGlyphFactoryProvider.GetGlyphFactory Return New TodoGlyphFactory() End Function
public IGlyphFactory GetGlyphFactory(IWpfTextView view, IWpfTextViewMargin margin) { return new TodoGlyphFactory(); }
Указание тега и средство создания тегов для Todo
Укажите связь между элементом пользовательского интерфейса, который был указан в предыдущих шагах и поле индикаторов путем создания тип и средство создания тегов для тега и экспортировать его, используя средство создания тегов для поставщика.
Указать тега и средство создания тегов для todo
Добавьте новый класс в проект и назовите его TodoTagger.
Добавьте следующие ввозы.
Imports System Imports System.Collections.Generic Imports System.ComponentModel.Composition Imports Microsoft.VisualStudio.Text Imports Microsoft.VisualStudio.Text.Tagging Imports Microsoft.VisualStudio.Text.Editor Imports Microsoft.VisualStudio.Text.Classification Imports Microsoft.VisualStudio.Utilities
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Tagging; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities;
Добавьте в проект класс TodoTag.
Friend Class TodoTag Implements IGlyphTag Public Sub New() MyBase.New() End Sub End Class
internal class TodoTag : IGlyphTag
Измените класс TodoTagger, реализующий ITagger type TodoTag.
Friend Class TodoTagger Implements ITagger(Of TodoTag)
internal class TodoTagger : ITagger<TodoTag>
к TodoTagger класс добавляет закрытые поля IClassifier и текст, который необходимо найти в диапазонах классификации.
Private m_classifier As IClassifier Private Const m_searchText As String = "todo"
private IClassifier m_classifier; private const string m_searchText = "todo";
Добавьте конструктор, который устанавливает классификатор.
Friend Sub New(ByVal classifier As IClassifier) m_classifier = classifier End Sub
internal TodoTagger(IClassifier classifier) { m_classifier = classifier; }
Реализуйте GetTags метод путем найти все диапазоны машинное классификации, имена которых содержат слово "примечания" и текст которых содержит искомый текст. Если искомый текст найден, создайте новую назад TagSpan type TodoTag.
Private Function GetTags(ByVal spans As NormalizedSnapshotSpanCollection) As IEnumerable(Of ITagSpan(Of TodoTag)) Implements ITagger(Of TodoTag).GetTags Dim list As List(Of ITagSpan(Of TodoTag)) list = New List(Of ITagSpan(Of TodoTag))() For Each span As SnapshotSpan In spans 'look at each classification span \ For Each classification As ClassificationSpan In m_classifier.GetClassificationSpans(span) 'if the classification is a comment If classification.ClassificationType.Classification.ToLower().Contains("comment") Then 'if the word "todo" is in the comment, 'create a new TodoTag TagSpan Dim index As Integer = classification.Span.GetText().ToLower().IndexOf(m_searchText) If index <> -1 Then list.Add(New TagSpan(Of TodoTag)(New SnapshotSpan(classification.Span.Start + index, m_searchText.Length), New TodoTag())) End If End If Next classification Next span Return list End Function
IEnumerable<ITagSpan<TodoTag>> ITagger<TodoTag>.GetTags(NormalizedSnapshotSpanCollection spans) { foreach (SnapshotSpan span in spans) { //look at each classification span \ foreach (ClassificationSpan classification in m_classifier.GetClassificationSpans(span)) { //if the classification is a comment if (classification.ClassificationType.Classification.ToLower().Contains("comment")) { //if the word "todo" is in the comment, //create a new TodoTag TagSpan int index = classification.Span.GetText().ToLower().IndexOf(m_searchText); if (index != -1) { yield return new TagSpan<TodoTag>(new SnapshotSpan(classification.Span.Start + index, m_searchText.Length), new TodoTag()); } } } } }
Declare a TagsChanged событие.
Public Event TagsChanged(ByVal sender As Object, ByVal e As Microsoft.VisualStudio.Text.SnapshotSpanEventArgs) Implements Microsoft.VisualStudio.Text.Tagging.ITagger(Of TodoTag).TagsChanged
public event EventHandler<SnapshotSpanEventArgs> TagsChanged;
Добавьте в проект класс TodoTaggerProvider, реализующий ITaggerProviderи экспортировать его a ContentTypeAttribute "код" и " a " TagTypeAttribute TodoTag.
<Export(GetType(ITaggerProvider)), ContentType("code"), TagType(GetType(TodoTag))> Friend Class TodoTaggerProvider Implements ITaggerProvider
[Export(typeof(ITaggerProvider))] [ContentType("code")] [TagType(typeof(TodoTag))] class TodoTaggerProvider : ITaggerProvider
Импортировать IClassifierAggregatorService.
<Import()> Friend AggregatorService As IClassifierAggregatorService
[Import] internal IClassifierAggregatorService AggregatorService;
Реализуйте CreateTagger``1 метод путем создания экземпляра TodoTagger.
Public Function CreateTagger(Of T As Microsoft.VisualStudio.Text.Tagging.ITag)(ByVal buffer As Microsoft.VisualStudio.Text.ITextBuffer) As Microsoft.VisualStudio.Text.Tagging.ITagger(Of T) Implements Microsoft.VisualStudio.Text.Tagging.ITaggerProvider.CreateTagger If buffer Is Nothing Then Throw New ArgumentNullException("buffer") End If Return TryCast(New TodoTagger(AggregatorService.GetClassifier(buffer)), ITagger(Of T)) End Function
public ITagger<T> CreateTagger<T>(ITextBuffer buffer) where T : ITag { if (buffer == null) { throw new ArgumentNullException("buffer"); } return new TodoTagger(AggregatorService.GetClassifier(buffer)) as ITagger<T>; }
Построение и тестирование кода
Для тестирования этого кода выполните построение решения TodoGlyphTest и запустите его в экспериментальном экземпляре.
Построение и тестирование решение TodoGlyphTest
Выполните построение решения.
Запустите проект, нажав клавишу F5. Второй экземпляр Visual Studio создается.
Убедитесь, что поле индикаторов показывается. (На Сервис меню выберите команду Параметры. На Текстовый редактор убедитесь в том, что страница Поле индикаторов подзапросы выборки.)
Откройте файл кода, который содержит комментарии. Добавьте машинное слово "todo" на один из разделов комментариев.
Источник света - синий кружок, который имеет синюю структуру должен появляться в поле индикаторов слева от окна кода.