共用方式為


讓自訂資料與 SharePoint 工具擴充功能產生關聯

您可以在 SharePoint 工具擴充功能的某些物件中加入自訂資料。 當您的一部分擴充功能中具有資料,且要在稍後從課程功能的其他程式碼存取,這將非常有用。 無需實作自訂方式來儲存和存取資料,您可以建立資料與擴充功能中物件的關聯,然後可在以後從相同物件擷取資料。

當您要保留 Visual Studio 中與特定項目相關的資料時,在物件中加入自訂資料也是很有用的。 SharePoint 工具擴充功能只會在 Visual Studio 中載入一次,所以擴充功能可隨時與多個不同項目 (例如專案、專案項目或 Server Explorer 節點) 搭配使用。 如果具有只與特定項目相關的自訂資料,您可以在表示該項目的物件中加入資料。

在 SharePoint 工具擴充功能的物件中加入自訂資料時,並不會保存資料。 資料只可在物件的生命週期期間使用。 在記憶體回收收回物件之後,會遺失資料。

在 SharePoint 專案系統的擴充功能中,您也可以儲存擴充功能卸載後仍然存在的字串資料。 如需詳細資訊,請參閱儲存 SharePoint 專案系統擴充功能的資料

可包含自訂資料的物件

您可以將自訂資料加入至實作 IAnnotatedObject 介面的 SharePoint 中工具物件模型的任何物件。 這個介面只會定義一個屬性,Annotations,它是自訂資料物件的集合。 下列型別會實作 IAnnotatedObject

加入和擷取自訂資料

若要在將自訂資料加入至 SharePoint 工具擴充功能中的物件,請取得要加入資料的物件的 Annotations 屬性,然後使用 IAnnotationDictionary.Add() 方法將資料加入至物件。

若要從 SharePoint 工具擴充功能中的物件擷取自訂資料,請取得該物件的 Annotations 屬性,然後使用下列其中一個方法:

  • IAnnotationDictionary.TryGetValue(). 如果資料物件存在,則此方法傳回 true,如果不存在,則傳回 false。 您可以使用此方法來擷取的實值型別或參考型別的執行個體。

  • IAnnotationDictionary.GetValue(). 如果資料物件存在,則此方法會傳回它,否則如果不存在則傳回 null。 您使用此方法只能擷取參考型別的執行個體。

下列程式碼範例會判斷特定資料物件是否已經與專案項目產生關聯。 如果資料物件尚未與專案項目關聯,則程式碼會將物件加入至專案項目的 Annotations 屬性。 若要在完整的範例內容中查看這個範例,請參閱 HOW TO:將屬性加入至自訂 SharePoint 專案項目類型

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
void projectItemTypeDefinition_ProjectItemPropertiesRequested(object sender, 
    SharePointProjectItemPropertiesRequestedEventArgs e)
{
    CustomProperties property;

    // If the properties object already exists, get it from the project item's annotations.
    if (!e.ProjectItem.Annotations.TryGetValue(out property))
    {
        // Otherwise, create a new properties object and add it to the annotations.
        property = new CustomProperties(e.ProjectItem);
        e.ProjectItem.Annotations.Add(property);
    }

    e.PropertySources.Add(property);
}

請參閱

工作

逐步解說:使用項目範本建立自訂動作專案項目 (第 1 部分)

逐步解說:擴充伺服器總管以顯示 Web 組件

其他資源

SharePoint 工具擴充功能的程式設計概念和功能

HOW TO:將屬性加入至 SharePoint 專案

HOW TO:將屬性加入至自訂 SharePoint 專案項目類型