C# WPF LiveCharts 切换图表关联到图例项

C# WPF LiveCharts toggle chart associated to legend item

你好谁能建议如何在图例项目上制作实时图表点击切换图表可见性(on/off),代码如下:

<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>

我尝试使用 Livecharts 示例,但分配 mouseleftbutton 事件不适用于图例项,而是在整个层上,如何仅对项目而不是整个图例层分配事件?

您必须覆盖默认模板才能在单个图例上接收 MouseLeftButtonDown 事件,因为默认图例只是系列的集合。

<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>