4

问题是:当我将IMvxMessanger的构造函数 DI 添加到ViewModel时,出现错误:“加载页面失败”;如果我要删除这个 DI,我的工具可以正常工作。顺便说一句,IHelloService不会给出这个错误,它只有在没有IMvxMessanger的情况下才能正常工作。

我遵循了本手册:https ://mvvmcross.com/docs/a-windows-universal-app-platform-project

Mvvm跨版本:4.4.0

代码示例:

第一视图模型

public class FirstViewModel : MvxViewModel
{
    private readonly IHelloService _helloService;
    private readonly IMvxMessenger _messenger;

    public FirstViewModel(IHelloService helloService, IMvxMessenger messenger)
    {
        _helloService = helloService;
        _messenger = messenger;
    }

    private string _hello = "Hello MvvmCross";
    public string Hello
    {
        get { return _hello; }
        set { SetProperty(ref _hello, value); }
    }
}

FirstView.xaml.cs

public sealed partial class FirstView : MvxWindowsPage
{
    public FirstView()
    {
        InitializeComponent();
    }
}

第一视图.xaml

<views:MvxWindowsPage
x:Class="MvvmCrossDocs.UWP.Views.FirstView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:MvvmCrossDocs.UWP.Views"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:views="using:MvvmCross.WindowsUWP.Views"
mc:Ignorable="d">

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
    <StackPanel>
        <TextBox Text="{Binding Hello, Mode=TwoWay}" />
        <TextBlock Text="{Binding Hello}" />
    </StackPanel>
</Grid>

设置

public class Setup : MvxWindowsSetup
{
    public Setup(Frame rootFrame) : base(rootFrame)
    {
    }

    protected override IMvxApplication CreateApp()
    {
        return new Core.App();
    }
}

App.xaml.cs 中的这一行

if (rootFrame.Content == null)
{
    var setup = new Setup(rootFrame);
    setup.Initialize();

    var start = Mvx.Resolve<IMvxAppStart>();
    start.Start();
}
4

1 回答 1

1

我认为问题在于您在 UWP 项目中缺少 MvxMessenger 的引导类。UWP 使用 Nuget 3 引入的 project.json 模板。目前,当您安装 nuget 包时,它们不允许将附加文件添加到您的项目中。

解决方法是手动添加 bootstrap 文件夹和相关插件bootstrap.cs文件,或者你可以在你的Setup.cs.

引导方法:

创建一个MessengerPluginBootstrap.cs

using MvvmCross.Platform.Plugins;

namespace <<YOUR_NAMESSPACE>>.Bootstrap
{
    public class MessengerPluginBootstrap
            : MvxPluginBootstrapAction<MvvmCross.Plugins.Messenger.PluginLoader>
    {
    }
}

Setup.cs 方法:

IMvxMessenger针对实现注册接口MvxMessengerHub

protected override void InitializeLastChance()
{
    base.InitializeLastChance();
    Mvx.RegisterSingleton<IMvxMessenger>(new MvxMessengerHub());
}
于 2016-12-22T15:57:57.410 回答