C# 在片段视图模型中未调用Init方法
我有一个片段,在init方法中,我试图显示一些数据,但是没有得到C# 在片段视图模型中未调用Init方法,c#,android,xamarin.android,mvvmcross,C#,Android,Xamarin.android,Mvvmcross,我有一个片段,在init方法中,我试图显示一些数据,但是没有得到 namespace MoneyCare.Core.ViewModels { public class HomeViewModel : MvxViewModel { public FirstViewModel First { get; set; } public SecondViewModel Second {
namespace MoneyCare.Core.ViewModels
{
public class HomeViewModel : MvxViewModel
{
public FirstViewModel First {
get;
set;
}
public SecondViewModel Second {
get;
set;
}
public ThirdViewModel Third {
get;
set;
}
public HomeViewModel()
{
First = new FirstViewModel();
Second = new SecondViewModel();
Third = new ThirdViewModel();
}
}
}
我的项目中有三个片段
namespace MoneyCare.Core.ViewModels
{
public class FirstViewModel: MvxViewModel
{
Friend _friend;
public List<Friend> AllFriends {
get;
set;
}
public string FriendUserName
{
get {
return _friend.FriendUserName;
}
set
{
_friend.FriendUserName = value;
RaisePropertyChanged(() => FriendUserName);
}
}
public void Init()
{
Task<List<Friend>> result = Mvx.Resolve<Repository>().getFriendsList();
result.Wait();
AllFriends = result.Result;
}
public ICommand check
{
get
{
return new MvxCommand(() =>
{
//Task<List<Friend>> result = Mvx.Resolve<Repository>().getFriendsList();
//result.Wait();
//AllFriends = result.Result;
ShowViewModel<CheckViewModel>();
});
}
}
//Opens Add Friends Activity
public ICommand OpenAddFriend
{
get
{
return new MvxCommand(() => ShowViewModel<AddFriendViewModel>());
}
}
}
}
我在Activity上也尝试了同样的方法,对于checkview Activity,它可以工作,但对于Fragment则不行。ViewModel的生命周期没有被执行,因为您没有使用MvvmCross加载它们,您只是像普通的.NET类一样构造它们。只有构造函数将实际运行。如果希望执行Init,则需要使用MvvmCross加载ViewModel,这通常通过使用ShowViewModel导航到它来完成
Android中活动包含的片段并不意味着您的ViewModel需要是HomeViewModel的子对象。调用ShowViewModel将确保FirstViewModel的InitFire。如何从HomeViewModel调用ShowViewModel?在HomeViewModel的Init方法中?否-在Init过程中,您不应该离开ViewModel。如果HomeViewModel是包含FirstViewModel链接到的片段的活动的ViewModel,请导航到FirstViewModel而不是HomeViewModel。确保Android使用MvxFragment属性加载片段的活动,如示例所示。