How to: Create a Scrollable Legend

  • 2 minutes to read

This example illustrates how to create a chart control with a scrollable legend. This may be required, for example, when a chart displays too many series, or a legend occupies too much space.

To accomplish this task, it is necessary to define a custom scrollable template and assign it to the Legend.Template property.

<Window x:Class="ScrollableLegend.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:dxc="http://schemas.devexpress.com/winfx/2008/xaml/charts"
        Title="MainWindow" Height="516" Width="803"  Loaded="Window_Loaded">
    <Grid>
        <dxc:ChartControl Name="chart">
            <!--region #legend-->
            <dxc:ChartControl.Legend>
                <dxc:Legend>
                    <dxc:Legend.Template>
                        <ControlTemplate TargetType="dxc:Legend">
                            <Border Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" 
                                    BorderBrush="{TemplateBinding BorderBrush}" Padding="{TemplateBinding Padding}">
                                <ScrollViewer MaxHeight="200">
                                    <dxc:LegendItemsControl ReverseItems="True" 
                                                            ItemTemplate="{TemplateBinding ItemTemplate}" 
                                                            LegendItems="{Binding Path=Items, RelativeSource={RelativeSource TemplatedParent}}">
                                        <dxc:LegendItemsControl.ItemsPanel>
                                            <ItemsPanelTemplate>
                                                <StackPanel Orientation="Vertical"/>
                                            </ItemsPanelTemplate>
                                        </dxc:LegendItemsControl.ItemsPanel>
                                    </dxc:LegendItemsControl>
                                </ScrollViewer>
                            </Border>
                        </ControlTemplate>
                    </dxc:Legend.Template>
                </dxc:Legend>
            </dxc:ChartControl.Legend>
            <!--endregion #legend-->
            <dxc:ChartControl.Diagram>
                <dxc:XYDiagram2D Name="xyDiagram" />
            </dxc:ChartControl.Diagram>
        </dxc:ChartControl>
    </Grid>
</Window>