Using ContentTypeBinding to associate content types with lists
In previous post we showed how to deploy a document and associate it with a content type. Even though the deploying and associating the document with content types was fairly easy we still had to manually associate the content type with desired document library. In this post I will show you how to use the ContentTypeBinding element to associate a content type to the existing document library.
You can use the content type project we created in previous post. Currently, we are deploying the document and a content type and then with the help of the DocumentTemplate element we are associating it to the content type. In order to automatically associate or bind the content type with an existing document library we need to create an Empty Element project item.
1. Right click the project name and select AddàNew Item.
2. From the list of templates, select Empty Element.
3. Name the project item "ContentTypeBinding" and click OK to create it.
A new folder with an empty Elements.xml file is added to the project. Double click the Elements.xml in the ContentTypeBinding folder we just added. As mentioned at the beginning, we are going to use the ContentTypeBinding element. This element can be used to bind a specific content type to an existing list or library. Let's create a new Document Library from the SharePoint home page and call it "My Documents". Switch back to the Visual Studio 2010 to add the ContentTypeBinding element to the empty Elements.xml file:
<?xml version="1.0" encoding="utf-8"?>
<ContentTypeBinding ListUrl="My Documents" ContentTypeId="[CONTENT TYPE ID]"/>
Explanation for the above snippet is very simple. We are pointing to the list and the content type ID we want to associate to that list. To get the content type ID you can either open the Elements.xml file inside the content type folder or use the Server Explorer:
1. In Visual Studio 2010, click Tools à Add SharePoint Connection item.
2. In the dialog that opens type the SharePoint URL and click OK to open the Server Explorer.
3. In the Server Explorer window expand the Team Site and Content Types node.
4. Locate the content type you want to associate (e.g. MyContentType - ContentType1).
5. With the desired content type selected, click F4 to open the Properties Window.
6. Locate the ID property - that's the content type ID we need for ContentTypeBinding.
7. Copy the ID and paste it to the empty elements' Elements.xml file to replace the [CONTENT TYPE ID] value.
We are all done! Press F5 to start debugging and navigate to the "My Documents" library. Click the Documents tab and then the New Document menu. You will notice the document we deployed with our solution now shows up in the menu which means that the content type was successfully associated with this document library. In the next post we will show how to achieve similar functionality (associate a content type with a document library) using feature event receivers.