【问题标题】:Navigate from Fragment to Activity MVVMCross从 Fragment 导航到 Activity MVVMCross
【发布时间】:2017-11-17 11:19:02
【问题描述】:

我正在努力在 ViewModel 级别执行从 Fragment 到 Activity 的导航。我有一个带有 DrawerLayout 的 Activity,这个 Activity 有一个 FrameLayout 来显示从 DrawerLayout 中选择的不同片段。该导航由该 Activity 的 ViewModel 执行,它调用每个 Fragment 的 ViewModel 来显示。在其中一个片段中,我添加了一个绑定 IMvxCommand 方法的按钮,以执行从片段到新 Activity 的导航,这就是我遇到问题的地方,因为当我单击按钮时没有任何反应。

在我的代码下方查找。

Fragment的ViewModel

public class MainFrameViewModel : ContentViewModel
    {
        readonly IMvxNavigationService navigationService;

        public MainFrameViewModel(IMvxNavigationService navigationService) : base(navigationService)
        {
            this.navigationService = navigationService;
        }

        public IMvxCommand GoMoreInfo
        {
            get
            {
                IMvxCommand navigateCommand = new MvxCommand(() => navigationService.Navigate<MoreInfoViewModel>());
                return navigateCommand;
            }
        }
    }

片段代码

[MvxFragmentPresentation(typeof(ContentViewModel), Resource.Id.frameLayout)]
    [Register("mvvmdemo.droid.views.fragments.MainFrameFragment")]
    public class MainFrameFragment : MvxFragment<MainFrameViewModel>
    {
        public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
        {
            return inflater.Inflate(Resource.Layout.MainFrame, container, false);
        }
    }

导航活动

[MvxActivityPresentation]
    [Activity(Label = "MoreInfoActivity")]
    public class MoreInfoActivity : MvxAppCompatActivity<MoreInfoViewModel> 
    {
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            SetContentView(Resource.Layout.MoreInfoLayout);
        }
    }

ContentViewModel 是包含 FrameLayout 和 DrawerLayout 的 Activity 的 ViewModel。

【问题讨论】:

    标签: xamarin mvvmcross


    【解决方案1】:

    您的绑定不起作用,因为您使用的是默认充气机,它对 MvvmCross 绑定一无所知。您可以通过在OnCreateView 中使用 MvvmCross 充气机来解决此问题。将return inflater.Inflate(Resource.Layout.MainFrame, container, false);调用改为return this.BindingInflate(Resource.Layout.MainFrame, null);

    另外,您忽略了IMvxNavigationService 的异步部分。从IMvxCommand 更改为IMvxAsyncCommand 和await 或返回Task 返回的Task 将是一种改进

    【讨论】:

    • 抱歉回复晚了,我上周出去了。我已将充气机更改为使用 MvvmCross 绑定充气机,但出现异常 System.NullReferenceException: Object reference not set to an instance of an object。
    猜你喜欢
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-27
    • 1970-01-01
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多