Search code examples
wpflivecharts

Livecharts change default legend


Here is my problem.

I am using LiveCharts to display some data. Everything fine until showing the legend which represents all the data displayed.

chart with legend

Is it possibile to show a legend based on for example color(Stroke) or DefaultGeometries?

Thanks in advance for your help,

Diego


Solution

  • I know this is a little late but I was looking to do something similar, so here is what I was able to come up with.

    You would need to create a new collection and follow the example for Live Charts Energy Predictions.

    First you need to set the LegendLocation="None" for the Chart

    <wpf:CartesianChart Hoverable="False" DataTooltip="{x:Null}" DisableAnimations="True" LegendLocation="None" Series="{Binding AllSeries, ElementName=FastGraphRoot}">
    

    New Legend Code (part that matters in .xaml):

    <ListBox Name="ListBox" MinHeight="250" ItemsSource="{Binding AllSeriesGroupByName, ElementName=FastGraphRoot}" Panel.ZIndex="1" BorderThickness="0" Background="Transparent">
            <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type wpf:LineSeries}">
                    <TextBlock Text="{Binding Title}" 
                               Foreground="{Binding Stroke}"
                               FontSize="24"/>
                </DataTemplate>
            </ListBox.ItemTemplate>
            <ListBox.ItemContainerStyle>
                <Style TargetType="{x:Type ListBoxItem}">
                    <Setter Property="Background" Value="Transparent" />
                    <Setter Property="Template">
                        <Setter.Value>
                            <ControlTemplate TargetType="{x:Type ListBoxItem}">
                                <ContentPresenter />
                            </ControlTemplate>
                        </Setter.Value>
                    </Setter>
                </Style>
            </ListBox.ItemContainerStyle>
        </ListBox>
    

    The Binded list would come from the original series but grouped, I have used a property for this:

    private SeriesCollection _allSeriesGroupByName = new SeriesCollection();
    public SeriesCollection AllSeriesGroupByName { get { return _allSeriesGroupByName; } set { _allSeriesGroupByName = value; OnPropertyChanged(); } }
    

    you could fill it simply with this code(or anything else you think is faster):

    var col = collection.GroupBy(g => ((LineSeries)g).Stroke).Select(p => p.First());
    AllSeriesGroupByName = new SeriesCollection();
    foreach (var c in col)
    {
        AllSeriesGroupByName.Add(c);
    }