我目前正在使用Livecharts,并试图将SeriesCollection绑定到DataGrid。可以绑定它,但这个系列有一些值,我希望DataGrid显示这些点。然而,它只显示了两个SeriesCollection项是绑定LiveCharts.SeriesAlgorithm.LineAlgorithm的,我不知道是否需要转换器来解决这个问题。
xaml.cs
public MyConstructor()
{
SeriesCollection = new SeriesCollection();
SeriesCollection.Add(reducedValuesLineSeries); // adds some points
SeriesCollection.Add(fullValuesLineSeries); // adds a line composed by many ponits
}
private SeriesCollection seriesCollection;
public SeriesCollection SeriesCollection
{
get => seriesCollection;
set
{
seriesCollection = value;
OnPropertyChanged();
}
}
xaml
<DataGrid ItemsSource="{Binding SeriesCollection}"/>
必须实现IValueConverter
才能从序列中提取这些点。显然,这些点深深地埋在";集合";。名称集合在这里相当具有误导性,因为SeriesCollection
与其说是实际集合,不如说是一个数据模型。整个库的实现相当混乱。
实际作为数据点的数据类型取决于您的实现。遗憾的是,你没有展示这些细节。
此示例假定数据项的类型为Point
:
ViewModel.cs
class ViewModel
{
public ViewModel()
{
var chartValues = new ChartValues<Point>();
// Create a sine
for (int x = 0; x < 361; x++)
{
var point = new Point() {X = x, Y = Math.Sin(x * Math.PI / 180)};
chartValues.Add(point);
}
this.SeriesCollection = new SeriesCollection
{
new LineSeries
{
Configuration = new CartesianMapper<Point>()
.X(point => point.X)
.Y(point => point.Y),
Title = "Series X",
Values = chartValues,
Fill = Brushes.DarkRed
}
};
}
}
系列集合指向PointsConverter.cs
class SeriesCollectionToPointsConverter : IValueConverter
{
#region Implementation of IValueConverter
public object Convert(object value, Type targetType, object parameter, CultureInfo culture) =>
value is SeriesCollection seriesCollection
? seriesCollection.SelectMany(series => series.Values as ChartValues<Point>)
: Binding.DoNothing;
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) =>
throw new NotSupportedException();
#endregion
}
主窗口.xaml
<Window>
<Window.DataContext>
<ViewModel />
</Window.DataContext>
<Window.Resources>
<SeriesCollectionToPointsConverter x:Key="SeriesCollectionToPointsConverter" />
</Window.Resources>
<DataGrid ItemsSource="{Binding SeriesCollection, Converter={StaticResource SeriesCollectionToPointsConverter}}" />
</Window>