Практическое руководство. Добавление свойства в расширение элемента проекта SharePoint
Расширение элемента проекта можно использовать для добавления свойства в любой элемент проекта SharePoint, который уже установлен в Visual Studio.Свойство отображается в окне Свойства при выборе элемента проекта в обозревателе решений.
В описании следующих действий предполагается, что расширение элемента проекта уже создано.Дополнительные сведения см. в разделе Практическое руководство. Создание расширения элемента проекта SharePoint.
Добавление свойства в расширение элемента проекта
Определите класс с общедоступным свойством, представляющим свойство, добавляемое к типу проектного элемента.Для добавления нескольких свойств к типу элемента проекта можно определить все свойства в одном классе или задать их в разных классах.
В методе Initialize реализации ISharePointProjectItemTypeExtension обработайте событие ProjectItemPropertiesRequested параметра projectItemType.
В обработчике событий для события ProjectItemPropertiesRequested добавьте экземпляр класса свойств в коллекцию PropertySources параметра аргументов события.
Пример
В следующем примере кода демонстрируется добавление свойства с именем Пример свойства к элементу проекта "Приемник события".
Imports System
Imports System.ComponentModel
Imports System.ComponentModel.Composition
Imports Microsoft.VisualStudio.SharePoint
Namespace Contoso.Examples.ProjectItemExtensionWithProperty
<Export(GetType(ISharePointProjectItemTypeExtension))> _
<SharePointProjectItemType("Microsoft.VisualStudio.SharePoint.EventHandler")> _
Friend Class ExampleProjectItemExtensionWithProperty
Implements ISharePointProjectItemTypeExtension
Private Sub Initialize(ByVal projectItemType As ISharePointProjectItemType) _
Implements ISharePointProjectItemTypeExtension.Initialize
AddHandler projectItemType.ProjectItemPropertiesRequested, AddressOf ProjectItemPropertiesRequested
End Sub
Private Sub ProjectItemPropertiesRequested(ByVal Sender As Object,
ByVal e As SharePointProjectItemPropertiesRequestedEventArgs)
Dim propertyObject As CustomProperties = Nothing
' If the properties object already exists, get it from the project item's annotations.
If False = e.ProjectItem.Annotations.TryGetValue(propertyObject) Then
' Otherwise, create a new properties object and add it to the annotations.
propertyObject = New CustomProperties(e.ProjectItem)
e.ProjectItem.Annotations.Add(propertyObject)
End If
e.PropertySources.Add(propertyObject)
End Sub
End Class
Friend Class CustomProperties
Private projectItem As ISharePointProjectItem
Friend Sub New(ByVal projectItem As ISharePointProjectItem)
Me.projectItem = projectItem
End Sub
Private Const TestPropertyId As String = "Contoso.ExampleProperty"
Private Const PropertyDefaultValue As String = "This is an example property."
<DisplayName("Example Property")> _
<DescriptionAttribute("This is an example property for project items.")> _
<DefaultValue(PropertyDefaultValue)> _
Public Property ExampleProperty As String
Get
Dim propertyValue As String = Nothing
' Get the current property value if it already exists; otherwise, return a default value.
If False = projectItem.ExtensionData.TryGetValue(TestPropertyId, propertyValue) Then
propertyValue = PropertyDefaultValue
End If
Return propertyValue
End Get
Set(ByVal value As String)
If value <> PropertyDefaultValue Then
' Store the property value in the ExtensionData property of the project item.
' Data in the ExtensionData property persists when the project is closed.
projectItem.ExtensionData(TestPropertyId) = value
Else
' Do not save the default value.
projectItem.ExtensionData.Remove(TestPropertyId)
End If
End Set
End Property
End Class
End Namespace
using System;
using System.ComponentModel;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint;
namespace Contoso.Examples.ProjectItemExtensionWithProperty
{
[Export(typeof(ISharePointProjectItemTypeExtension))]
[SharePointProjectItemType("Microsoft.VisualStudio.SharePoint.EventHandler")]
internal class ExampleProjectItemExtensionWithProperty : ISharePointProjectItemTypeExtension
{
public void Initialize(ISharePointProjectItemType projectItemType)
{
projectItemType.ProjectItemPropertiesRequested +=
projectItemType_ProjectItemPropertiesRequested;
}
void projectItemType_ProjectItemPropertiesRequested(object sender,
SharePointProjectItemPropertiesRequestedEventArgs e)
{
CustomProperties propertyObject;
// If the properties object already exists, get it from the project item's annotations.
if (!e.ProjectItem.Annotations.TryGetValue(out propertyObject))
{
// Otherwise, create a new properties object and add it to the annotations.
propertyObject = new CustomProperties(e.ProjectItem);
e.ProjectItem.Annotations.Add(propertyObject);
}
e.PropertySources.Add(propertyObject);
}
}
internal class CustomProperties
{
private ISharePointProjectItem projectItem;
internal CustomProperties(ISharePointProjectItem projectItem)
{
this.projectItem = projectItem;
}
private const string PropertyId = "Contoso.ExampleProperty";
private const string PropertyDefaultValue = "This is an example property.";
[DisplayName("Example Property")]
[DescriptionAttribute("This is an example property for project items.")]
[DefaultValue(PropertyDefaultValue)]
public string ExampleProperty
{
get
{
string propertyValue;
// Get the current property value if it already exists; otherwise, return a default value.
if (!projectItem.ExtensionData.TryGetValue(PropertyId, out propertyValue))
{
propertyValue = PropertyDefaultValue;
}
return propertyValue;
}
set
{
if (value != PropertyDefaultValue)
{
// Store the property value in the ExtensionData property of the project item.
// Data in the ExtensionData property persists when the project is closed.
projectItem.ExtensionData[PropertyId] = value;
}
else
{
// Do not save the default value.
projectItem.ExtensionData.Remove(PropertyId);
}
}
}
}
}
Общие сведения о коде
Чтобы обеспечить использование одного и того же экземпляра класса CustomProperties при каждом возникновении события ProjectItemPropertiesRequested, пример кода добавляет объект свойств в свойство Annotations элемента проекта, когда это событие происходит впервые.Когда событие происходит снова, код извлекает этот объект.Дополнительные сведения об использовании свойства Annotations для связывания данных с элементами проекта см. в разделе Связь пользовательских данных с расширениями средств SharePoint.
Для сохранения изменений в значении свойства метод доступа set для свойства ExampleProperty сохраняет новое значение в свойстве ExtensionData объекта ISharePointProjectItem, с которым это свойство связано.Дополнительные сведения об использовании свойства ExtensionData для сохранения данных вместе с элементами проекта см. в разделе Сохранение данных в расширениях системы проектов SharePoint.
Определение поведения настраиваемых свойств
Отображение и поведение настраиваемого свойства можно определить в окне Свойства, применив к определению этого свойства атрибуты из пространства имен System.ComponentModel.Во многих сценариях удобно использовать перечисленные ниже атрибуты.
DisplayNameAttribute — задает имя свойства, которое отображается в окне Свойства.
DescriptionAttribute — задает строку описания, которая отображается в нижней части окна Свойства при выборе данного свойства.
DefaultValueAttribute — задает значение свойства по умолчанию.
TypeConverterAttribute — задает настраиваемое преобразование между строкой, отображаемой в окне Свойства, и нестроковым значением свойства.
EditorAttribute — задает пользовательский редактор, который необходимо использовать для изменения свойства.
Компиляция кода
Для таких примеров требуется проект библиотеки классов со ссылками на следующие сборки.
Microsoft.VisualStudio.SharePoint
System.ComponentModel.Composition
Развертывание расширения
Чтобы развернуть расширение, создайте пакет расширения Visual Studio (VSIX) для сборки и всех остальных файлов, которые предположительно будут распространяться с расширением.Дополнительные сведения см. в разделе Разработка расширений для средств SharePoint в Visual Studio.
См. также
Задачи
Пошаговое руководство. Расширение типа проектного элемента SharePoint
Основные понятия
Практическое руководство. Создание расширения элемента проекта SharePoint