Modifying Layer Style
To modify the styling for a layer, retrieve the layer definition from the repository, make changes to it, store it back to the repository, and refresh the layer.
To retrieve the layer definition, get its resource identifier from the map layer. Get the resource content and deserialize it using an XmlSerializer object.
AcMapMap currentMap = AcMapMap.GetCurrentMap();
MgLayerCollection layers = currentMap.GetLayers();
MgResourceService rs =
AcMapServiceFactory.GetService(MgServiceType.ResourceService)
as MgResourceService;
// Get the layer definition. Convert it to an XML string
// stored in a byte reader.
AcMapLayer layer1 = layers.GetItem(layerName) as AcMapLayer;
MgResourceIdentifier layerDefId = layer1.GetLayerDefinition();
MgByteReader layerReader = rs.GetResourceContent(layerDefId);
// Deserialize it to create a LayerDefinition object.
XmlSerializer layerDefSerializer = new
XmlSerializer(typeof(LayerDefinition));
LayerDefinition xmlLayerDef =
layerDefSerializer.Deserialize(new
StringReader(layerReader.ToString()))
as LayerDefinition;
Updating the LayerDefinition object is similar to creating a new one. Find the correct elements and set their values. For example, the following changes the foreground color for the area rule in the first scale range, then it updates the layer definition in the resource repository and refreshes the layer.
// Should be a VectorLayerDefinitionType
if (xmlLayerDef.Item is VectorLayerDefinitionType)
{
VectorLayerDefinitionType xmlVectorLayerDef =
xmlLayerDef.Item as VectorLayerDefinitionType;
// Check the rules for the first scale range.
// Only update rules if they are the correct type.
object[] items = xmlVectorLayerDef.VectorScaleRange[0].Items;
foreach (object item in items)
{
Type type = item.GetType();
if (type.Name == typeof(AreaRule[]).Name)
{
AreaRule[] areaRules = item as AreaRule[];
// OK, got the correct area rule. Set the foreground color.
if (areaRules.Length > 0)
{
areaRules[0].Item.Fill.ForegroundColor = newColor;
}
}
}
// Now convert it back to an XML string and update the
// resource.
using (StringWriter writer = new StringWriter())
{
// Get the xml string
layerDefSerializer.Serialize(writer, xmlLayerDef);
// Create the resource
byte[] unicodeBytes =
Encoding.Unicode.GetBytes(writer.ToString());
byte[] utf8Bytes =
Encoding.Convert(Encoding.Unicode,
Encoding.UTF8, unicodeBytes);
MgByteSource source =
new MgByteSource(utf8Bytes, utf8Bytes.Length);
// Update the resource in Map
rs.SetResource(layer1.LayerDefinition,
source.GetReader(), null);
layer1.ForceRefresh();
}
}