How To: Toggle the visibility for a LYR or group layer legend using ArcObjects


Instructions provide a code sample that shows how to toggle the visibility of the Table of Contents legend for a group layer or LYR file.



  1. Start ArcMap.
  2. Create a new UIButtonControl: How To: Create a new UIButtonControl​
    For more information on creating a UIControl, see the ArcGIS Desktop Help topic: 'Creating custom commands with VBA and UI Controls'
  3. Right-click the UIButtonControl and select View Source.
  4. Copy this code into the UIButtonControl's click event.
    Dim pMxDoc As IMxDocument
    Dim pGroupLayer As IGroupLayer
    Dim pLayer As ILayer
    Dim pLegendInfo As ILegendInfo
    Dim pLegendGroup As ILegendGroup
    Set pMxDoc = ThisDocument
    Set pLayer = pMxDoc.SelectedLayer
    If Not TypeOf pLayer Is IGraphicsLayer Then
    If TypeOf pLayer Is IGroupLayer Then
        Set pGroupLayer = pLayer
        pGroupLayer.Expanded = Not pGroupLayer.Expanded
        Set pLegendInfo = pLayer
        Set pLegendGroup = pLegendInfo.LegendGroup(0)
        pLegendGroup.Visible = Not pLegendGroup.Visible
    End If
    End If
  5. Select a layer file in the Table of Contents and press the button to test the code sample.