Есть ли способ удалить только одну серию строк из легенды в графике wpf Livecharts? - PullRequest
0 голосов
/ 07 апреля 2020

Так что я использую Livecharts для wpf и сделал SeriesCollection, которая содержит несколько LineSeries и StackedAreas. Пока все хорошо.

Я отображаю все графики на одной диаграмме, поэтому каждая легенда или область сгруппированы в легенде. Моя проблема в том, что мне нужно удалить только одну LineSeries из легенды.

В документальном фильме для LiveCharts есть только способ удалить всю легенду или создать собственную, но это не совсем то, что мне нужно. Я подумал, что должен быть простой способ просто удалить один график из легенды.

1 Ответ

0 голосов
/ 07 апреля 2020

Вы должны переопределить легенду по умолчанию, переопределив ControlTemplate из CartesianChart.ChartLegend.
Затем создайте свою собственную легенду, введя новую коллекцию внутри вашей модели, которая содержит все LineSeries вас и sh создать легенду для.

В этом примере используется ListBox для хранения элементов легенды и переопределение ListBox.ItemsTemplate для фактического оформления элементов.

Модель publi c class PointShapeLineExample {publi c PointShapeLineExample () {InitializeComponent ();

        SeriesCollection = new SeriesCollection
        {
            new LineSeries
            {
                Title = "Series 1",
                Values = new ChartValues<double> { 4, 6, 5, 2 ,4 }
            },
            new LineSeries
            {
                Title = "Series 2",
                Values = new ChartValues<double> { 6, 7, 3, 4 ,6 },
                PointGeometry = null
            },
            new LineSeries
            {
                Title = "Series 3",
                Values = new ChartValues<double> { 4,2,7,2,7 },
                PointGeometry = DefaultGeometries.Square,
                PointGeometrySize = 15
            }
        };

        Labels = new[] {"Jan", "Feb", "Mar", "Apr", "May"};
        YFormatter = value => value.ToString("C");

        //modifying the series collection will animate and update the chart
        SeriesCollection.Add(new LineSeries
        {
            Title = "Series 4",
            Values = new ChartValues<double> {5, 3, 2, 4},
            LineSmoothness = 0, //0: straight lines, 1: really smooth lines
            PointGeometry = Geometry.Parse("m 25 70.36218 20 -28 -20 22 -8 -6 z"),
            PointGeometrySize = 50,
            PointForeground = Brushes.Gray
        });

        //modifying any series values will also animate and update the chart
        SeriesCollection[3].Values.Add(5d);

        // Only create a legend for the first two series
        LegendSeries = new List<LineSeries>(SeriesCollection.Take(2));
    }

    public IEnumerable<LineSeries> LegendSeries { get; set; }
    public SeriesCollection SeriesCollection { get; set; }
    public string[] Labels { get; set; }
    public Func<double, string> YFormatter { get; set; }

}

Просмотр

<Window>
  <Window.DataContext>
    <PointShapeLineExample />
  </Window.DataContext>    

  <CartesianChart Series="{Binding SeriesCollection}" 
                  LegendLocation="Left" >
    <CartesianChart.ChartLegend>
      <DefaultLegend>
        <DefaultLegend.Template>
          <ControlTemplate TargetType="DefaultLegend">
            <ListBox ItemsSource="{Binding LegendSeries}"
                     VerticalAlignment="Center"
                     HorizontalAlignment="Center"
                     IsHitTestVisible="False">
              <ListBox.ItemTemplate>
                <DataTemplate DataType="{x:Type LineSeries}">
                  <StackPanel Orientation="Horizontal">
                    <Rectangle Fill="{Binding Stroke}" 
                               Height="12" 
                               Width="12" 
                               Margin="0,0,4,0" />
                    <TextBlock Text="{Binding Title}" />
                  </StackPanel>
                </DataTemplate>
              </ListBox.ItemTemplate>
            </ListBox>
          </ControlTemplate>
        </DefaultLegend.Template>
      </DefaultLegend>
    </CartesianChart.ChartLegend>

    <CartesianChart.AxisY>
      <Axis Title="Sales" LabelFormatter="{Binding YFormatter}" />
    </CartesianChart.AxisY>
    <CartesianChart.AxisX>
      <Axis Title="Month" Labels="{Binding Labels}" />
    </CartesianChart.AxisX>
  </CartesianChart>
</Window>
...