我有以下简单的导航流程:
ViewModel1 => ViewModel2 => ViewModel3
当ViewModel3关闭时,我使用Message插件向ViewModel发布一些需要添加到ViewModel1列表中的信息。不幸的是没有任何事情发生(我提出了NotifChanged)。在我看来,这是因为它不是从UI调用的。
获得更新清单的最佳方法是什么?我没有在ViewModel中看到ViewModel从另一个ViewModel返回时调用的任何方法,即当ViewModel3关闭时。
编辑: 示例代码:
public class WarehouseInViewModel : MvxViewModel
{
public WarehouseInViewModel(IMvxMessenger messenger)
{
mvxMessenger = messenger;
myToken = mvxMessenger.Subscribe<mAcceptMessage>(OnMyMessageArrived);
}
public override void Start()
{
base.Start();
}
private readonly IMvxMessenger mvxMessenger;
private MvxSubscriptionToken myToken;
private List<mProduct> productItems;
public List<mProduct> ProductItems
{
get { return productItems; }
set
{
productItems = value;
RaisePropertyChanged(() => ProductItems);
}
}
private MvxCommand<AcceptMenuItem> buttonCommand;
public ICommand ButtonCommand
{
get
{
return buttonCommand = buttonCommand ?? new MvxCommand<AcceptMenuItem>(MenuClick);
}
}
private void OnMyMessageArrived(mAcceptMessage myMessage)
{
mProduct product = mProduct.GetById(myMessage.ProductId);
//Something more ...
// There I want to update my Listview which is binded to ProductItems
ProductItems.Add(product);
RaisePropertyChanged(() => ProductItems);
}
public async void MenuClick(AcceptMenuItem menu)
{
ShowViewModel<WarehouseInScanViewModel>();
}
}
来自Third ViewModel的最重要的方法(我们假设secont ViewMOdel只打开第三个,并且它已正确关闭)):
public void ButtonNextClick()
{
vxMessenger.Publish(new mAcceptMessage(this, productId, scannedLocation.Id, productQuantity));
Close(this);
}
所以,当我从第三个VM回来时,我想要重新发布ListView。我不能从OnMyMessageArrived那里做到,因为它不在UI线程中。
答案 0 :(得分:0)
您可以使用静态字段添加GlobalVars.cs
静态类(可能是创建“服务”文件夹并将其放入内部以使其更清晰),并将其用作ViewModel1
中列表的数据源。然后,您需要做的就是在List
GlobalVars.cs
ViewModel3
的{{1}}添加数据。
服务/ GlobalVars.cs
public static class GlobalVars
{
public static List<CustomClass> aGlobalVariable;
}
ViewModel1.cs
using Services;
...
public CustomClass LocalVariable
{
get { return GlobalVars.aGlobalVariable; }
set
{
GlobalVars.aGlobalVariable = value;
...
}
}
//refresh purpose
public void refresh()
{
RaisePropertyChanged(() => LocalVariable);
}
ViewModel3.cs
//just add the GlobalVars List when you need it
GlobalVars.aGlobalVariable.Add(new CustomClass());
要刷新ListView
,当您返回ViewModel1
时,只需从活动中调用refresh()
方法即可。以下是您在活动中访问ViewModel
的方式。
View1.cs
ViewModel1 vm;
...
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
...
vm = ViewModel as ViewModel1;
...
}
//what you want to do is refreshing the list on resume
protected override void OnResume()
{
base.OnResume()
vm.refresh();
... //other things you might want to do
}
希望这个答案有所帮助。