You can use filtering to retrieve all materials in the document. Every Material object in the Document is identified by a unique name.
The following example illustrates how to use the material name to get material.
|
Code Region 19-5: Getting a material by name |
FilteredElementCollector elementCollector = new FilteredElementCollector(document);
elementCollector.WherePasses(new ElementClassFilter(typeof(Material)));
IList<Element> materials = elementCollector.ToElements();
Material floorMaterial = null;
string floorMaterialName = "Default Floor";
foreach (Element materialElement in materials)
{
Material material = materialElement as Material;
if (floorMaterialName == material.Name)
{
floorMaterial = material;
break;
}
}
if (null != floorMaterial)
{
TaskDialog.Show("Revit","Material found.");
}
Note: To run the sample code, make sure the material name exists in your document. All material names for the current document are located under the Manage tab (Project Settings panel
|
There are two ways to create a new Material object in the API.
Duplicate an existing Material
Add a new Material.
When using the Duplicate() method, the returned Material object is the same type as the original.
|
Code Region 19-6: Duplicating a material |
private bool DuplicateMaterial(Material material)
{
bool duplicated = false;
//try to duplicate a new instance of Material class using duplicate method
//make sure the name of new material is unique in MaterailSet
string newName = "new" + material.Name;
Material myMaterial = material.Duplicate(newName);
if (null == myMaterial)
{
TaskDialog.Show("Revit", "Failed to duplicate a material!");
}
else
{
duplicated = true;
}
return duplicated;
}
|
Use the static method Material.Create() to add a new Material directly. No matter how it is applied, it is necessary to specify a unique name for the material and any assets belonging to the material. The unique name is the Material object key.
|
Code Region 19-7: Adding a new Material |
//Create the material
ElementId materialId = Material.Create(document, "My Material");
Material material = document.GetElement(materialId) as Material;
//Create a new property set that can be used by this material
StructuralAsset strucAsset = new StructuralAsset("My Property Set", StructuralAssetClass.Concrete);
strucAsset.Behavior = StructuralBehavior.Isotropic;
strucAsset.Density = 232.0;
//Assign the property set to the material.
PropertySetElement pse = PropertySetElement.Create(document, strucAsset);
material.SetMaterialAspectByPropertySet(MaterialAspect.Structural, pse.Id);
|
To delete a material use:
Document.Delete() is a generic method. See Editing Elements for details.