Search code examples
c#wpflivecharts

C# WPF LiveCharts toggle chart associated to legend item


Hello Can anyone advice how to make LiveCharts on legend item click toggle charts visibility(on/off), code below:

<lvc:CartesianChart Height="312" Width="389" LegendLocation="Bottom" Pan="None">
                        <lvc:CartesianChart.ChartLegend>
                            <lvc:DefaultLegend Tag="1" MouseLeftButtonDown="DefaultLegend_Click">
                            </lvc:DefaultLegend>
                        </lvc:CartesianChart.ChartLegend>
                        <lvc:CartesianChart.DataTooltip>
                            <lvc:DefaultTooltip SelectionMode="SharedYInSeries" />
                        </lvc:CartesianChart.DataTooltip>
                        <lvc:CartesianChart.Series>
                            <lvc:LineSeries Visibility="Visible" Values="9,5,5,1,0,8" Title="Chart One"/>
                            <lvc:LineSeries x:Name="FirstChart" Visibility="Visible" Values="19,15,15,11,10,18" Title="Chart Two"/>
                        </lvc:CartesianChart.Series>
                    </lvc:CartesianChart>

I tried to use Livecharts examples but assigning mouseleftbutton event works not on legend item, but on whole layer, how can assign event on just item not on whole legend layer?


Solution

  • You'll have to override default template in order to receive MouseLeftButtonDown event on individual legend as default legend is just a collection of series.

    <lvc:DefaultLegend.Template>
        <ControlTemplate>
            <ItemsControl ItemsSource="{Binding Series}">
                <ItemsControl.ItemsPanel>
                    <ItemsPanelTemplate>
                        <StackPanel Orientation="Horizontal" />
                    </ItemsPanelTemplate>
                </ItemsControl.ItemsPanel>
                <ItemsControl.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal" MouseLeftButtonDown="StackPanel_MouseLeftButtonDown">
                            <Ellipse Height="16"
                                     Width="16"
                                     Stroke="{Binding Stroke}"
                                     StrokeThickness="{Binding StrokeThickness}" />
                            <TextBlock Text="{Binding Title}" Padding="5" Margin="5" />
                        </StackPanel>
                    </DataTemplate>
                </ItemsControl.ItemTemplate>
            </ItemsControl>
        </ControlTemplate>
    </lvc:DefaultLegend.Template>