[英]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.