Cannot create an instance of “MainViewModel”

北战南征 提交于 2019-12-05 17:44:44

Try to make the binding on the constructor of the MainWindow and remove it from the XAML:

public MainWindow()
{
   InitializeComponent();
   DataContext = new MainViewModel();
}

This should work ..

You are mixing two different ways of setting DataContext. Select one and go with that.

If your viewmodels have default constructors (i.e. constructors without arguments) you could do it all in xaml:

  <Window x:Class="MVVM_DemoAppl.Views.MainWindow"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:ViewModel="clr-namespace:MVVM_DemoAppl.ViewModels"
     Title="MainWindow" Height="350" Width="525">
     <Window.DataContext>
         <! This instantiates a MainViewModel and binds this view to the viewmodel.
         <ViewModel:MainViewModel/> 
     </Window.DataContext>

Or you leave Window.DataContext be unset in your view and do it separately somewhere else, perhaps in OnStartup() as earlier.

public partial class App : Application
{
   protected override void OnStartup(StartupEventArgs e)
   {
      base.OnStartup(e);
      var mainWindow = new MainWindow();
      var viewModel = new MainViewModel();
      mainWindow.DataContext = viewModel; // Bind the ViewModel to the Window Datacontext.
      mainWindow.Show();
   }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!