【问题标题】:MvvmCross; How to RaisePropertyChange from another ViewModelMvvmCross;如何从另一个 ViewModel 中引发PropertyChange
【发布时间】:2017-02-24 15:02:05
【问题描述】:

我有一个 ShoppingCart listView,其中包含 items绑定ShoppingCartViewModel。当我 单击 到一个 item 时,它会将我带到 ItemInfoFragment,它 绑定ItemInfoViewModel强>。

ItemInfoFragment 我有一个 按钮,它删除 item删除它来自 ShoppingCart listview

我的问题是;在我删除项目 后退按钮返回到我的以前 activityShoppingCart listView仍然显示删除的Item强>。

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

【问题讨论】:

标签: c# android listview mvvm mvvmcross


【解决方案1】:

我相信你有几个选择:

共享持久存储

如果您使用SQLiteRealm 等存储/缓存解决方案,可用于在页面之间读取和修改相同的购物车数据。然后,您可以使用视图生命周期事件(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 Pluginmessages 发送回购物车ViewModel。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-25
    • 1970-01-01
    相关资源
    最近更新 更多