![](/img/trans.png)
[英]How to copy list from class to another class in Windows Phone 8.1 with Parsing Pages
[英]Adding items to a List in another class Windows Phone 8.1
我发现了类似的问题,但没有设法解决我的问题。
我有一个Windows Phone 8.1运行时项目。 让我们考虑一个类和2页。
Item类包含对象的属性
public class Item
{
public string firstname { get; set; }
public string lastname { get; set; }
public Item(string fname, string lname)
{
this.firstname = fname;
this.lastname = lname;
}
}
项目的MainPage创建项目列表
public List<Item> list = new List<Item>();
并使用函数将项目添加到列表中
list.Add(new Item(string1, string2));
然后,我还有另一个名为NewItem的页面。 我使用此代码将项目添加到列表中,但未显示(例如代码未执行,但实际上会执行)
MainPage m = new MainPage();
m.list.Add(new Item(string1, string2));
为什么不将项目添加到MainPage的列表中? 我使用Frame.Navigate()而不是NavigationService类进行导航,这是一个问题吗? 谢谢!
与第一行:
MainPage m = new MainPage();
m.list.Add(new Item(string1, string2));
您正在创建MainPage的新实例,而不是您从中导航的实例。 因此,对该实例的变量所做的任何更改都不会在您的上一页上生效。 还要注意,一旦超出范围,这个新实例将被垃圾回收。
解决方案之一可能是使list
成为静态变量-然后您就可以像MainPage.list.Add(...);
一样从应用程序中获取它MainPage.list.Add(...);
。 有关静态变量的更多信息,请参见MSDN 。
其他解决方案可能是传递上一页的处理程序,然后访问其变量。
还要注意,如果您使用list
作为UI元素的来源,最好将其设置为ObservableCollection ,这样它将自动将其更改通知UI。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.