Prism MVVM:“未为类型定义无参数构造函数”将 ViewModel 绑定到 View 时出错

时间:2021-01-21 12:02:12

标签: c# wpf .net-core mvvm prism

我正在创建一个简单的 WPF 应用程序,它有一个视图和视图模型,它在视图模型中使用依赖注入来执行计算。

App.xaml.cs

public partial class App : Application
{
   protected override void OnStartup(StartupEventArgs e)
   {
      IUnityContainer container = new UnityContainer();
      container.RegisterType<ICharacterCountService, CharacterCountService>();
      container.RegisterType<IMathService, MathService>();
      container.RegisterType<IMainWindowViewModel, MainWindowViewModel>();
      ViewModelLocationProvider.Register<MainWindow, MainWindowViewModel>();
      MainWindow mainWindow = container.Resolve<MainWindow>();
      mainWindow.Show();
   }
}

MainWindow.xaml

<Window x:Class="MyFirstMVVM.Views.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:MyFirstMVVM"
           xmlns:prism="http://prismlibrary.com/"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="400"
        prism:ViewModelLocator.AutoWireViewModel="True">

MainWindowViewModel 中的构造函数:

public MainWindowViewModel(IMathService mathService, ICharacterCountService characterCountService)
{
   _mathService = mathService;
   _characterCountService = characterCountService;

   AddCommand = new DelegateCommand(Add);
   CountCommand = new DelegateCommand(Count);
}

如果视图模型中有无参数构造函数,则似乎只能使用 ViewModelLocator,在这种情况下,我将无法注入 CharacterCountServiceMathService。我是否必须使用另一种方式将视图 DataContext 设置为视图模型?

我也尝试过直接在视图中设置 DataContext,但出现类似错误:XAML error, no parameterless constructor.

1 个答案:

答案 0 :(得分:2)

当您构建 Prism 应用程序时,您的 App 类应该派生自 PrismApplication。它设置了 Prism 所需的所有基础设施,以及您使用的 ViewModelLocator。它会自动将当前容器连接到 ViewModelLocationProvider 以解析类型。这意味着,任何带有注册到容器的参数的构造函数都可以毫不费力地工作。

然而,默认情况下,在没有任何初始化的情况下,ViewModelLocationProvider 将使用反射命名空间中的 Activator 来实例化如下类型,最终是 requires a parameterless constructor

type => Activator.CreateInstance(type);

因此,您有两种选择可以使其发挥作用。

  • App 派生您的主应用程序类型 PrismApplication 并正确初始化它。要开始,请查看Override the Existing Application Object

  • 自己初始化 ViewModelLocationProvider 类型工厂。

    ViewModelLocationProvider.SetDefaultViewModelFactory((view, type) => container.Resolve(type));
    

至于 XAML 声明,这与使用无参数构造函数在代码中实例化类型完全相同。由于您没有提供,因此您会收到此错误。

var mainWindowViewModel = new MainWindowViewModel();
相关问题