繁体   English   中英

如何将数据从应用程序页面类传递到ViewModel类WP8

[英]how to pass data from an application page class to a ViewModel class WP8

在我的WP8应用程序页面中,我正在生成我用于绘制图表的ViewModel的数据。生成的数据作为List传递给ViewModel。这是我有点问题,因为它们是不同的类并且列表的可见范围不会扩展到ViewModel的集合。

这是应用程序页面中的数据(这是我正在做的一个例子):

namespace M
{

public partial class SampleRecord : PhoneApplicationPage
{

    List<Record> r_List = new List<Record>();
    public SampleRecord()
    {
        InitializeComponent();

    }

    private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)
    {
      //after proceesing the data
        r_List.Add(1, 100);
        r_List.Add(2, 200);
        r_List.Add(3, 300);
    }
    }
    }

ViewModel类:

public class ViewModel
{
    public ObservableCollection<Record> Collection { get; set; }
    public ViewModel()
    {
        Collection = new ObservableCollection<Record>();
        GenerateData();
    }
    private void GenerateData()
    {

        for(int i<0; i<r_List.Count; i++){\

         this.Collection.Add(add elements of the list to the collection);
        }


    }
}

}

尝试在App.xaml.cs中声明List,以便可以在eveywhere访问它,但在应用程序页面类中无法识别它。

如果您正在使用MVVM,那么在视图中拥有数据源是非常不可能的 如果你坚持在那里,那么你没有使用MVVM。

但是,如果您只是在视图的代码后面创建一个DependencyProperty来保存数据集合,那么您可以从那里将数据绑定到它。 我们假设你的财产叫做Collection ......

Collection = new ObservableCollection<Record>();
GenerateData();

...你可以从视图中绑定数据,如下所示:

<ListBox ItemsSource="{Binding Collection, RelativeSource={RelativeSource 
    AncestorType={x:Type YourLocalPrefix:YourView}}}" ... />

但是,我无法强调将视图与数据访问分开的重要性。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM