MvvmCross; 如何从另一个ViewModel RaisePropertyChange

我有一个ShoppingCart listView包含绑定ShopingCartViewModel的项目 。 当我点击一个项目时,它会将我带到ItemInfoFragment ,它绑定ItemInfoViewModel

ItemInfoFragment中,我有一个按钮 ,用于删除 项目并将其从ShoppingCart 列表视图中 删除

我的问题是 ; 删除 项目 并按 后退按钮返回到我之前的 活动后ShoppingCart listView显示删除项目

我的问题是; 当我退出ItemInfoFragment时,如何在ShoppingCartViewModel中RaisePropertyChange?

我相信你有几个选择:

共享持久存储

如果您使用SQLite或Realm等存储/缓存解决方案,可以使用它来读取和修改页面之间的相同购物车数据。 然后,您可以使用视图生命周期事件( OnResume [Android]或ViewWillAppear [iOS])从缓存中检索最新的事件。

或者,如果购物车数据量很小,您可以将其读/写到MvvmCross Settings Plugin 。 您只需序列化和反序列化对象,因为您只能保存基本类型,如字符串,bool,int等。

dependency injection共享实例

您可以使用可在多个ViewModel之间共享的共享类实例创建内存缓存。 此类属性可以直接绑定到各种视图。 对列表的任何更改都将更新绑定到它的所有视图。 需要注意的一点是,如果需要此实例类占用的内存空间,则必须手动处理清理。

例:

示例模型

 public class ItemInfo { public int Id { get; set; } public string Name { get; set; } public double Price { get; set; } } 

共享类实例和接口

 public interface ISharedShoppingCart { MvxObservableCollection ShoppingCartItems { get; set; } } public class SharedShoppingCart : MvxNotifyPropertyChanged, ISharedShoppingCart { MvxObservableCollection _shoppingCartItems; public MvxObservableCollection ShoppingCartItems { get { return _shoppingCartItems; } set { SetProperty(ref _shoppingCartItems, value); } } } 

确保注册类和接口

 public class App : MvxApplication { public override void Initialize() { /* Other registerations*/ Mvx.LazyConstructAndRegisterSingleton(); } } 

共享ViewModel中的示例用法

 public class ShopingCartViewModel : MvxViewModel { readonly ISharedShoppingCart _sharedShoppingChart; public ShopingCartViewModel(ISharedShoppingCart sharedShoppingChart) { _sharedShoppingChart = sharedShoppingChart; } public MvxObservableCollection 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插件将消息发送回购物车ViewModel。