您可以使用 MVVM 模式将多个 LineSeries 绑定到 WPF 中的 oxyplot 吗?

Can you bind multiple LineSeries to an oxyplot in WPF using MVVM pattern?

我正在尝试在 Oxyplot 中使用 C# 在 WPF 中的一个 <oxy:PlotView /> 元素中绘制多个 LineSeries 元素,其中我使用的是 MVVM 模式。假设我遇到(假设的)情况,即我正在跟踪具有随时间变化的位置的汽车。假设我有以下文件:

在初始化时,我创建了三个汽车元素(在 DisplayViewModel.cs : Cars = new List<Car>{ new Car(), ...}; 中)及其相应的位移与时间数据 PlotData = new List<DataPoint>{ new DataPoint(0,1), new DataPoint(1,4), ...};CarName

DisplayView.xaml (1):

<ListBox ItemsSource="{Binding Path=Cars}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <oxy:Plot Title="{Binding CarName}" Height="400" Width="500">
                    <oxy:Plot.Series>
                        <oxy:LineSeries ItemsSource="{Binding Path=PlotData}"/>
                    </oxy:Plot.Series>
                </oxy:Plot>
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

这按预期工作。它显示了一个 <ListBox /> 和三个(单独的)图表。然而,这不是我想要实现的。我想做如下事情:

DisplayView.xaml (2):

<ItemsControl ItemsSource="{Binding Path=Cars}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding Path=CarName}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

这会按预期显示三个单独的汽车名称,所以我知道我已正确连接数据源。但是,用 <oxy:Plot><oxy:Plot.Series>...</oxy:Plot.Series></oxy:Plot> 包装此 <ItemsControl>...</ItemsControl> 元素并将 <TextBlock /> 元素更改为 <oxy:LineSeries /> 元素并将其 ItemsSource 属性 绑定到前面提到的DataPoint 字段产生错误 A value of type 'ItemsControl' cannot be added to a collection or dictionary of type 'collection`1'.The specified value cannot be assigned to the collection. The following type was expected: "Series"..

DisplayView.xaml(不起作用):

<oxy:Plot Title="Displacement plot">
    <oxy:Plot.Series>
        <ItemsControl ItemsSource="{Binding Path=Cars}">
            <ItemsControl.ItemTemplate>
                <DataTemplate>
                    <oxy:LineSeries ItemsSource="{Binding Path=PlotData}"/>
                </DataTemplate>
            </ItemsControl.ItemTemplate>
        </ItemsControl>
    </oxy:Plot.Series>
</oxy:Plot>

我是 MVVM 模式的新手 - 以及一般的 C# 和 WPF 编程 - 我看到 DisplayView.xaml.cs 代码隐藏文件需要为空。使用后面的代码时,我可以让三个 LineSeries 在一张图中显示,但我正在尝试利用 MVVM 的强大功能。有人可以指点我应该如何解决这个问题吗?我只是(还)没有足够的经验来玩代码,所以一些解释将不胜感激。我需要添加什么文件,我需要创建什么方法以及在哪里创建这些文件?这甚至可以按照我设想的方式实现吗?

亲切的问候,

汤姆

我想我掌握了这个概念(在写下我的想法和问题后 post),所以我正在回答我自己的问题。在 DisplayView.xaml 中,我添加了一个 <PlotView /><oxy:PlotView x:Name="DisplayPlotView" Model="{Binding PlotModel}" />。据我所知,我还在 DisplayViewModel.cs 中创建了一个 PlotModel,这符合 MVVM 模式。我通过 Cars 循环添加不同的系列:

foreach(Car car in Cars)
    {
        PlotModel.Series.Add(car.PlotData);
    }

我现在在 Car.cs 中将 PlotData 设为 LineSeries。这在一张图中显示了三条线。