Managing graphic features

Once you've created a graphics layer, you need to add graphics to it to display data. In most cases, you'll create graphics using geometries that have been created by actions such as executing a query or drawing a shape on the map. To add a graphic, you need to do the following:

The following sections show how to write code to add a graphic feature. All the .NET code shown here is written in C#.

Adding graphic features

While it's possible to add graphics to a map using XAML, you'll usually use .NET code (that is, code-behind). The following steps assume you are writing code in the code-behind of a window with XAML that defines a Map and a GraphicsLayer. The Map has an x:Name of MyMap, and the GraphicsLayer has an ID of MyGraphicsLayer.

  1. Before you can add a graphic, you must get a reference to a GraphicsLayer. Retrieve a GraphicsLayer as follows:
    GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
    
  2. In many cases, you'll get a reference to a graphic or a list of graphics by handling the events of objects such as tasks. In other instances, such as with draw surfaces, you'll create a graphic from a geometry. The code that follows assumes that you have already gotten a reference to a list of graphics and stored them in a variable called graphicsList. Define a loop to iterate through the graphics as follows:
    GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
    foreach (Graphic graphic in graphicsList)
    {
    }
    
  3. Apply a symbol to each graphic. The following code assumes that a symbol called MySymbol has already been declared. For information about creating symbols, see Symbols and renderers.
    GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
    foreach (Graphic graphic in graphicsList)
    {
        graphic.Symbol = MySymbol;
    }
    
    CautionCaution:

    If you have a renderer set on your GraphicsLayer, and the GraphicsLayer.RendererTakesPrecedence property is set to true (which is the default), the symbols set on individual graphics will be overwritten by the renderer. Set RendererTakesPrecendence to false to use the symbols set on individual graphics and only apply the renderer to the graphics without a symbol set.

  4. Once the symbol has been applied, add the graphic to the GraphicsLayer. This causes the graphic to be drawn on the map.
    GraphicsLayer graphicsLayer = MyMap.Layers["MyGraphicsLayer"] as GraphicsLayer;
    foreach (Graphic graphic in graphicsList)
    {
        graphic.Symbol = MySymbol;
        graphicsLayer.Graphics.Add(graphic);
    }
    
1/23/2012