Share via


Clase SPFieldLink

Representa una referencia de columna única (también conocido como campo) que se incluye en un tipo de contenido.

Jerarquía de la herencia

System.Object
  Microsoft.SharePoint.SPFieldLink

Espacio de nombres:  Microsoft.SharePoint
Ensamblado:  Microsoft.SharePoint (en Microsoft.SharePoint.dll)

Sintaxis

'Declaración
Public Class SPFieldLink
'Uso
Dim instance As SPFieldLink
public class SPFieldLink

Comentarios

Si desea realizar un seguimiento de determinados metadatos del elemento en un tipo de contenido, se puede hacer referencia a una columna que representa que los metadatos. Sin embargo, no se puede crear una columna en un tipo de contenido; debe crear la columna por separado y, a continuación, hacer referencia a él en la definición de tipo de contenido. Como resultado, cuando se agrega una columna a un tipo de contenido, el tipo de contenido contiene una referencia a la columna (o campo), en lugar de la columna (o campo) propio.

La referencia contiene un subconjunto de las propiedades de la definición de campo completo. Estas son las propiedades que se pueden personalizar para la columna ya que existe en el tipo de contenido.

Para obtener más información, consulte Fields and Field References.

El objeto SPContentType contiene un SPFieldLinkCollection y un objeto SPFieldCollection .

El objeto SPFieldCollection proporciona una vista combinada de los atributos de una columna, ya que existen en el tipo de contenido especificado. Cada objeto SPField representa todos los atributos de una definición de columna o campo, combinados con los atributos que se han reemplazado en la referencia de campo para ese tipo de contenido.

Cuando tiene acceso a un objeto SPField en un tipo de contenido, SharePoint Foundation combina la definición de campo con la referencia de campo y devuelve el objeto SPField resultante. Esto resulta útil porque no es necesario que buscar una definición de campo y todos los atributos en la definición del campo que se reemplazan por la referencia de campo para ese tipo de contenido.

No hay una correlación de 1 a 1 entre los elementos de los objetos SPFieldLinkCollection y SPFieldCollection . Para cada objeto SPFieldLink que agregar a un tipo de contenido, SharePoint Foundation agrega un objeto SPField correspondiente que representa la vista combinada de la columna tal como se define en el tipo de contenido.

Nota

SharePoint Foundation no es compatible con la herencia de la clase SPFieldLink .

Ejemplos

El ejemplo siguiente muestra una aplicación de consola que crea un tipo de contenido, se aplica a una lista y agrega referencias a los campos en el nivel de sitio y de lista.

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();
        }
    }
}

La aplicación imprime el siguiente resultado en la consola.

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...

Seguridad para subprocesos

Los miembros static (Shared en Visual Basic) públicos de este tipo son seguros para subprocesos. No se garantiza que los miembros de instancias sean seguros para los subprocesos.

Vea también

Referencia

Miembros SPFieldLink

Espacio de nombres Microsoft.SharePoint

Otros recursos

Fields and Field References

FieldRef Element (ContentType)

Introduction to Columns

Introduction to Content Types