我相信你有几个选择:
共享持久存储
如果您使用SQLite 或Realm 等存储/缓存解决方案,可用于在页面之间读取和修改相同的购物车数据。然后,您可以使用视图生命周期事件(OnResume[Android] 或 ViewWillAppear[iOS])从缓存中检索最新的。
或者,如果购物车数据很小,您可以将其读/写到MvvmCross Settings Plugin。您只需要序列化和反序列化您的对象,因为您只能保存基本类型,如字符串、布尔值、int 等。
依赖注入共享实例
您可以通过使用可以在多个 ViewModel 之间共享的共享类实例来创建内存缓存。此类属性可以直接绑定到您的各种视图。对列表的任何更改都会更新绑定到它的所有视图。需要注意的一点是,如果需要 this 实例类占用的内存空间,则必须手动进行清理。
例子:
示例模型
public class ItemInfo
{
public int Id { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
共享类实例和接口
public interface ISharedShoppingCart
{
MvxObservableCollection<ItemInfo> ShoppingCartItems { get; set; }
}
public class SharedShoppingCart : MvxNotifyPropertyChanged, ISharedShoppingCart
{
MvxObservableCollection<ItemInfo> _shoppingCartItems;
public MvxObservableCollection<ItemInfo> ShoppingCartItems
{
get { return _shoppingCartItems; }
set { SetProperty(ref _shoppingCartItems, value); }
}
}
确保注册类和接口
public class App : MvxApplication
{
public override void Initialize()
{
/* Other registerations*/
Mvx.LazyConstructAndRegisterSingleton<ISharedShoppingCart, SharedShoppingCart>();
}
}
共享 ViewModel 中的示例用法
public class ShopingCartViewModel : MvxViewModel
{
readonly ISharedShoppingCart _sharedShoppingChart;
public ShopingCartViewModel(ISharedShoppingCart sharedShoppingChart)
{
_sharedShoppingChart = sharedShoppingChart;
}
public MvxObservableCollection<ItemInfo> ShoppingCartItems
{
get { return _sharedShoppingChart.ShoppingCartItems; }
set { _sharedShoppingChart.ShoppingCartItems = value; }
}
}
public class ItemInfoViewModel : MvxViewModel
{
readonly ISharedShoppingCart _sharedShoppingCart;
public ItemInfoViewModel(ISharedShoppingCart sharedShoppingCart)
{
_sharedShoppingCart = sharedShoppingCart;
}
void RemoveItemFromCart(int id)
{
_sharedShoppingCart.ShoppingCartItems
.Remove(_sharedShoppingCart.ShoppingCartItems.Single(x => x.Id == id));
}
}
发布/订阅
您可以使用MvvmCross Messenger Plugin 将messages 发送回购物车ViewModel。