Sorry I forgot to mention that if you have a hierarchy of group layers, you have also to adapt the C# code to take into account this hierarchy.
Here is the code which should work whatever the number of group levels:
void Legend_Refreshed(object sender, ESRI.ArcGIS.Client.Toolkit.Legend.RefreshedEventArgs e)
{
SetLayerItemImageSource(e.LayerItem);
}
private void SetLayerItemImageSource(LayerItemViewModel layerItem)
{
if (layerItem.LegendItems != null && layerItem.LegendItems.Any()) // if there is a legend item
layerItem.ImageSource = layerItem.LegendItems.First().ImageSource; // set the image of the sublayer with the image of the first legenditem
// Call recursively SetLayerItemImageSource
if (layerItem.LayerItems != null)
{
foreach(var sublayerItem in layerItem.LayerItems)
SetLayerItemImageSource(sublayerItem);
}
}
Note that instead of using your own listbox and a binding to a legend control, you can also retemplate the legend control to use a listbox.
For example with this template:
<esri:Legend Map="{Binding ElementName=MyMap}" LayerItemsMode="Flat" ShowOnlyVisibleLayers="False" LayerIDs="California" Refreshed="Legend_Refreshed">
<esri:Legend.Template>
<ControlTemplate TargetType="esri:Legend">
<ListBox ItemsSource="{TemplateBinding LayerItemsSource}" >
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<CheckBox IsChecked="{Binding IsEnabled, Mode=TwoWay}" IsEnabled="{Binding IsInScaleRange}" VerticalAlignment="Center"/>
<TextBlock Text="{Binding Label}" VerticalAlignment="Center"/>
<Image Source="{Binding ImageSource}" Margin="3,0"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</ControlTemplate>
</esri:Legend.Template>
<esri:Legend>
you get this result: