Класс SPFieldLink
Представляет ссылку на одного столбца (поля), который включен в тип контента.
Иерархия наследования
System.Object
Microsoft.SharePoint.SPFieldLink
Пространство имен: Microsoft.SharePoint
Сборка: Microsoft.SharePoint (в Microsoft.SharePoint.dll)
Синтаксис
'Декларация
Public Class SPFieldLink
'Применение
Dim instance As SPFieldLink
public class SPFieldLink
Замечания
Если вы хотите отслеживать конкретные метаданные элемента в типе контента, можно ссылаться на столбец, который представляет метаданные. Тем не менее невозможно создать столбец в типе контента; необходимо создать столбец отдельно и затем сослаться на него в определении типа контента. В результате при добавлении столбца к типу контента типа контента содержит ссылку на столбец (или поля), а не на основе столбца (или поля) самого.
Справочные материалы по содержит подмножество свойств определения полного поля. Это свойства, которые можно настроить для столбца, как оно существует в типе контента.
Дополнительные сведения см. в статье Fields and Field References.
Объект SPContentType содержит SPFieldLinkCollection и объект SPFieldCollection .
Объект SPFieldCollection предоставляет объединенное представление столбца атрибутов, как они существуют в указанном типе контента. Каждый объект SPField представляет все атрибуты определения поля или столбца, в сочетании с помощью этих атрибутов, которые были переопределены в ссылке на поле для этого типа контента.
При доступе к SPField объекта в типе контента SharePoint Foundation объединяет определение поля со ссылкой на поле и возвращает результирующую объект SPField . Это полезно, так как нет необходимости выполнять поиск определения полей и все атрибуты определения поля, измененные с помощью ссылки полей для этого типа контента.
Существует корреляции 1-1 между элементами SPFieldLinkCollection и SPFieldCollection объектов. Для каждого объекта SPFieldLink , добавьте к типу контента SharePoint Foundation добавляет соответствующего объекта SPField , который представляет объединенное представление этот столбец, как определено в типе контента.
Примечание
SharePoint Foundation не поддерживает наследование от класса SPFieldLink .
Примеры
В следующем примере показано консольное приложение, которое создается тип контента, относится к списку и добавляет ссылки на поля на уровне сайта и списка.
Imports System
Imports Microsoft.SharePoint
Module ConsoleApp
Sub Main()
Dim site As SPSite = New SPSite("https://localhost")
Try
Dim web As SPWeb = site.OpenWeb()
Try
Dim contentTypeName As String = "Spec"
Dim listTitle As String = "Product Specs"
Dim docType As SPContentType = web.AvailableContentTypes("Document")
' Create a content type.
Dim siteContentType As New SPContentType(docType, _
web.ContentTypes, contentTypeName)
' Add the content type to the site collection.
siteContentType = web.ContentTypes.Add(siteContentType)
' Change the name of the Title field in the content type.
siteContentType.FieldLinks("Title").DisplayName = "Product"
' Add a field to the site field collection.
Dim siteField As SPField = AddField("Owner", SPFieldType.Text, web.Fields)
' Reference the field in the content type.
AddFieldLink(siteField, siteContentType)
siteContentType.Update()
' Create and configure a document library.
Dim listId As Guid = web.Lists.Add(listTitle, _
"A library of product specifications", _
SPListTemplateType.DocumentLibrary)
Dim library As SPDocumentLibrary = CType(web.Lists(listId), SPDocumentLibrary)
library.OnQuickLaunch = True
library.ContentTypesEnabled = True
library.EnableFolderCreation = False 'Hide "Folder" on the New menu
library.Update()
' Add the site content type to the library.
Dim listContentType As SPContentType = library.ContentTypes.Add(siteContentType)
' Add a field to the list field collection.
Dim listField As SPField = AddField("SKU", SPFieldType.Text, library.Fields)
' Reference the field in the list version of the new content type.
AddFieldLink(listField, listContentType)
listContentType.Update()
' Remove the document content type.
Dim id As SPContentTypeId = library.ContentTypes(docType.Name).Id
library.ContentTypes.Delete(id)
library.Update()
' Review our work.
Console.WriteLine("Site content type")
PrintFieldNames(siteContentType)
Console.WriteLine("List content type")
PrintFieldNames(listContentType)
Finally
web.Dispose()
End Try
Finally
site.Dispose()
End Try
Console.Write("Press ENTER to continue...")
Console.ReadLine()
End Sub
Function AddField(ByVal title As String, ByVal type As SPFieldType, _
ByRef fields As SPFieldCollection) As SPField
' If the field is not in the collection,
If Not (fields.ContainsField(title)) Then
' Add it.
fields.Add(title, type, False)
End If
Return fields.GetField(title)
End Function
Sub AddFieldLink(ByRef field As SPField, ByRef contentType As SPContentType)
' Is the FieldLink in the collection?
Dim fieldLink As SPFieldLink = contentType.FieldLinks(field.Id)
If fieldLink Is Nothing Then ' No, so add it.
fieldLink = New SPFieldLink(field)
contentType.FieldLinks.Add(fieldLink)
End If
End Sub
Sub PrintFieldNames(ByVal contentType As SPContentType)
For Each link As SPFieldLink In contentType.FieldLinks
Dim field As SPField = contentType.Fields(link.Id)
' Screen out system fields.
If field.Reorderable AndAlso field.InternalName <> "FileLeafRef" Then
Console.WriteLine("FieldLink.DisplayName = {0}", link.DisplayName)
End If
Next link
Console.WriteLine()
End Sub
End Module
using System;
using Microsoft.SharePoint;
namespace Test
{
class ConsoleApp
{
static void Main(string[] args)
{
using (SPSite site = new SPSite("https://localhost"))
{
using (SPWeb web = site.OpenWeb())
{
string contentTypeName = "Spec";
string listTitle = "Product Specs";
SPContentType docType = web.AvailableContentTypes["Document"];
// Create a content type.
SPContentType siteContentType = new SPContentType(docType,
web.ContentTypes,
contentTypeName);
// Add the content type to the site collection.
siteContentType = web.ContentTypes.Add(siteContentType);
// Change the name of the Title field in the content type.
siteContentType.FieldLinks["Title"].DisplayName = "Product";
// Add a field to the site field collection.
SPField siteField = AddField("Owner", SPFieldType.Text, web.Fields);
// Reference the field in the content type.
AddFieldLink(siteField, siteContentType);
siteContentType.Update();
// Create and configure a document library.
Guid listId = web.Lists.Add(listTitle,
"A library of product specifications",
SPListTemplateType.DocumentLibrary);
SPDocumentLibrary library = (SPDocumentLibrary)web.Lists[listId];
library.OnQuickLaunch = true;
library.ContentTypesEnabled = true;
library.EnableFolderCreation = false; // Hide "Folder" on the New menu
library.Update();
// Add the site content type to the library.
SPContentType listContentType = library.ContentTypes.Add(siteContentType);
library.Update();
// Add a field to the list field collection.
SPField listField = AddField("SKU", SPFieldType.Text, library.Fields);
// Reference the field in the list version of the content type.
AddFieldLink(listField, listContentType);
listContentType.Update();
// Remove the document content type from the library.
SPContentTypeId id = library.ContentTypes[docType.Name].Id;
library.ContentTypes.Delete(id);
library.Update();
// Review our work.
Console.WriteLine("Site content type");
PrintFieldNames(siteContentType);
Console.WriteLine("List content type");
PrintFieldNames(listContentType);
}
}
Console.Write("Press ENTER to continue...");
Console.ReadLine();
}
static SPField AddField(string title, SPFieldType type, SPFieldCollection fields)
{
// If the field is not in the collection,
if (!fields.ContainsField(title))
{
// Add it.
fields.Add(title, type, false);
}
return fields.GetField(title);
}
static void AddFieldLink(SPField field, SPContentType contentType)
{
// Is the FieldLink in the collection?
SPFieldLink fieldLink = contentType.FieldLinks[field.Id];
if (fieldLink == null) // No, so add it.
{
fieldLink = new SPFieldLink(field);
contentType.FieldLinks.Add(fieldLink);
}
}
static void PrintFieldNames(SPContentType contentType)
{
foreach (SPFieldLink link in contentType.FieldLinks)
{
SPField field = contentType.Fields[link.Id];
// Screen out system fields.
if (field.Reorderable && field.InternalName != "FileLeafRef")
Console.WriteLine("FieldLink.DisplayName = {0}", link.DisplayName);
}
Console.WriteLine();
}
}
}
В консоли приложение выведет следующие данные:
Site content type
FieldLink.DisplayName = Product
FieldLink.DisplayName = Owner
List content type
FieldLink.DisplayName = Product
FieldLink.DisplayName = Owner
FieldLink.DisplayName = SKU
Press ENTER to continue...
Потокобезопасность
Любые общедоступные элементы static (Shared в Visual Basic) этого типа являются потокобезопасными. Не гарантируется, что любые элементы экземпляров потокобезопасны.
См. также
Справочные материалы
Пространство имен Microsoft.SharePoint