In LiveCharts, I am creating a bunch of LineSeries with a foreach loop. How do I access a particular line series in this list? I'd like to show and hide them, with a checkbox in WPF.
foreach (var item in ElementsList)
{
ch.Series.Add(new LineSeries
{
Values = item.Value.ElementValues,
Title = item.Value.ElementName,
Visibility = Visibility.Hidden
});
}
Chart = ch;
I'd like to be able to click a checkbox and have a specific series show/hide in the chart.
It can be done in a few ways. I am using the MVVM pattern here but could be also adapt a just back-code for the view as well
First I created a class that combines two information LineSeries and bool property for visibility (could also use converter here). The class has also simple logic that when state of bool is changed it also change visibility property of series.
public class LineSeriesVisible : INotifyPropertyChanged
{
private Series _LineSerie;
public Series LineSerie
{
get { return _LineSerie; }
set
{
if (value != _LineSerie)
{
_LineSerie = value;
NotifyPropertyChanged();
}
}
}
private bool _Visibility;
public bool Visibility
{
get { return _Visibility; }
set
{
if (value != _Visibility)
{
_Visibility = value;
if (LineSerie != null)
{
if (value == true)
{
LineSerie.Visibility = System.Windows.Visibility.Visible;
}
else
{
LineSerie.Visibility = System.Windows.Visibility.Collapsed;
}
}
NotifyPropertyChanged();
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
Next is to declare the collection for line-series, for wpf application use ObserableCollection
private ObservableCollection<LineSeriesVisible> _LineSeriesVisib;
public ObservableCollection<LineSeriesVisible> LineSeriesVisib
{
get { return _LineSeriesVisib; }
set
{
if (value != _LineSeriesVisib)
{
_LineSeriesVisib = value;
NotifyPropertyChanged();
}
}
}
Last part is binding it to the ItemsControl control. We biding the collection to itemscontrol control and as datatemplate use checkbox.
<ItemsControl ItemsSource="{Binding LineSeriesVisib,
Mode=TwoWay,NotifyOnSourceUpdated=True,
UpdateSourceTrigger=PropertyChanged}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<CheckBox Content="{Binding LineSerie.Title}" IsChecked="{Binding Visibility}"/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Last option is to add your line-series to obseravablecolleciton afrer your loop.
LineSeriesVisib = new ObservableCollection<LineSeriesVisible>(ch.Series);
Let me know if it works. It works for me :)