WPF绑定找不到数据项 [英] WPF Binding can't find data item

查看:71
本文介绍了WPF绑定找不到数据项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对数据绑定和MVVM的概念还很陌生,因此在过去的几天里我一直在尝试.基本上,我想做的是使用LiveCharts库,我想从上传的CSV文件中同时显示多个图表.

I am quite new to the concept of data binding and MVVM, so I've been trying it out the past couple of days. Basically, what I'm trying to do is using the LiveCharts library, I want to display multiple charts at the same time from an uploaded CSV file.

到目前为止,我做得不错,但是现在我正在编写代码,这样,如果我想在一个图表中增加X轴的单位,就可以与其他图表同时进行.(在上下文中,x轴以时间戳为单位,并且不同的图表应具有相同的时间戳,但在相同的时间戳下具有不同的ID和不同的值)

I am doing well so far, but now I am writing code so that if I want to increase the units in the X-Axis in one chart, I can do so simultaneously with the others. (For context, the x-axis is in the timestamp unit, and the different charts should have the same timestamp, but different IDs and different values under the same timestamp)

UI中的代码是这样的(省略了一些我认为不必要的代码):

The code in my UI is like this (omitted some of the code I think is unnecessary):

<ItemsControl ItemsSource="{Binding SeriesViews}" VerticalAlignment="Top">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Border Background="White">
                     <lvc:CartesianChart Series="{Binding}" Pan="X">
                        <lvc:CartesianChart.AxisX>
                            <lvc:Axis RangeChanged="Axis_RangeChanged" 
                                      MinValue="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}, Path=DataContext.Xmin}" 
                                      MaxValue="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Grid}}, Path=DataContext.Xmax}"
                                      Separator="{x:Static lvc:DefaultAxes.CleanSeparator}">
                            </lvc:Axis>
                        </lvc:CartesianChart.AxisX>
                    </lvc:CartesianChart>
                </Border>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

另一端是这样的:

    public GraphData gd;
    public Graphs()
    {
        InitializeComponent();
    }

    public void GenerateCSVList(string csvPath)
    {
        using (var reader = new StreamReader(csvPath))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            ExcelRecords = csv.GetRecords<Emotions>().ToList();
        }

        gd = new GraphData();
        gd.Xmin = 0;
        gd.Xmax = 5;
        gd.SeriesViews = ReturnChart();
        this.DataContext = gd;
    }

    public ObservableCollection<SeriesCollection> ReturnChart()
        {
            ObservableCollection<SeriesCollection> ChartCollection = new ObservableCollection<SeriesCollection>();
            //Draw charts here
            return ChartCollection
        }

    public class GraphData : INotifyPropertyChanged
        {
            public ObservableCollection<SeriesCollection> SeriesViews { get; set; }
            private double _xmin;
            private double _xmax;

            public event PropertyChangedEventHandler PropertyChanged;
            protected virtual void OnPropertyChanged(string propertyName = null)
            {
                if (PropertyChanged != null)
                    PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
            }
            public double Xmin
            {
                get { return _xmin; }
                set
                {
                    _xmin = value;
                    OnPropertyChanged("Xmin");
                }
            }
            public double Xmax
            {
                get { return _xmax; }
                set
                {
                    _xmax = value;
                    OnPropertyChanged("Xmax");
                }
            }
        }

尽管当前存在最小值和最大值,但我目前仍收到此错误:

I'm currently getting this error though for both the min and max values:

System.Windows.Data Error: 4 : Cannot find source for binding with reference 'RelativeSource FindAncestor, AncestorType='System.Windows.Controls.Grid', AncestorLevel='1''. BindingExpression:Path=DataContext.Xmax; DataItem=null; target element is 'Axis' (Name=''); target property is 'MaxValue' (type 'Double')

我希望朝着正确的方向前进,因为所有这些对我来说都是很新的.绑定是否缺少我的东西?我认为通过将它们放在一个类中,我将能够从UI访问它们.为什么我可以查看SeriesView,但不能查看同一类的Xmin和Xmax?

I would appreciate a nudge in the right direction, since all of this is quite new to me. Is there something I missed with the binding? I thought by putting them in one class I would be able to access them from the UI. Why am I able to view the SeriesViews, but not the Xmin and Xmax from the same class?

推荐答案

弄清楚了.以下是工作代码:

Figured it out. The following is the working code:

<lvc:Axis RangeChanged="Axis_RangeChanged" DisableAnimations="True" Position="LeftBottom" 
      MinValue="{Binding DataContext.Xmin, Source={x:Reference Root}}" 
      MaxValue="{Binding DataContext.Xmax, Source={x:Reference Root}}" 
      Separator="{x:Static lvc:DefaultAxes.CleanSeparator}">

我在其中将UserControl命名为Root

Where I named my UserControl as Root

这篇关于WPF绑定找不到数据项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆