[英]How can I WPF bind dynamically created checkboxes to dynamically created series in LiveCharts?
[英]How can I hide and show LiveCharts series with dynamically created chart, and dynamic checkboxes?
在LiveCharts中,我創建了一堆帶有foreach循環的LineSeries。 如何訪問此列表中的特定行系列? 我想在WPF中顯示一個復選框來顯示和隱藏它們。
foreach (var item in ElementsList)
{
ch.Series.Add(new LineSeries
{
Values = item.Value.ElementValues,
Title = item.Value.ElementName,
Visibility = Visibility.Hidden
});
}
Chart = ch;
我希望能夠單擊一個復選框,並在圖表中顯示/隱藏特定系列。
它可以通過幾種方式完成。 我在這里使用MVVM模式,但也可以適應視圖的后備代碼
首先,我創建了一個類,它結合了兩個信息LineSeries和bool屬性以實現可見性(這里也可以使用轉換器)。 該類還具有簡單的邏輯,即當bool的狀態改變時,它也改變了系列的可見性屬性。
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));
}
}
接下來是為line-series聲明集合,為wpf應用程序使用ObserableCollection
private ObservableCollection<LineSeriesVisible> _LineSeriesVisib;
public ObservableCollection<LineSeriesVisible> LineSeriesVisib
{
get { return _LineSeriesVisib; }
set
{
if (value != _LineSeriesVisib)
{
_LineSeriesVisib = value;
NotifyPropertyChanged();
}
}
}
最后一部分是將它綁定到ItemsControl控件。 我們將集合綁定到itemscontrol控件並作為datatemplate使用復選框。
<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>
最后一個選項是在你的循環后添加你的系列到obseravablecolleciton。
LineSeriesVisib = new ObservableCollection<LineSeriesVisible>(ch.Series);
如果有效,請告訴我。 這個對我有用 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.