无法创建&QUOT实例; MainViewModel" [英] Cannot create an instance of "MainViewModel"

查看:557
本文介绍了无法创建&QUOT实例; MainViewModel"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建实现使用观察的集合(以下MVVM模式)数据绑定一个DataGrid到数据库的简单WPFapplication。



App.xaml.cs类



 公共部分类应用:应用
{
保护覆盖无效OnStartup(StartupEventArgs E)
{
base.OnStartup(E);
变种的主窗口=新的主窗口();
VAR视图模型=新MainViewModel();
mainWindow.Show();
}
}

当我尝试将其绑定到我的XAML我有提出了以下错误:



Cannnot打造MainViewModel



实例XAML代码:

 <窗口x:类=MVVM_DemoAppl.Views.MainWindow
的xmlns =HTTP: //schemas.microsoft.com/winfx/2006/xaml/presentation
的xmlns:X =http://schemas.microsoft.com/winfx/2006/xaml
的xmlns:视图模型= CLR的命名空间:MVVM_DemoAppl.ViewModels
标题=主窗口HEIGHT =350WIDTH =525>
<! - 错误是在这里提出 - >
< Window.DataContext>
<视图模型:MainViewModel />
< /Window.DataContext>



如何克服这种错误?谢谢



PS:我已经张贴上的 MSDN论坛但我的整个代码,请看看为了更好的理解。



在用户的建议,我必须保持我的OnStartup()这个方法?



 公共部分类应用:应用
{
保护覆盖无效OnStartup(StartupEventArgs E)
{
base.OnStartup(E);
}
}


解决方案

尝试使结合在主窗口的构造函数,并从XAML中删除:

 公共主窗口()
{
的InitializeComponent();
的DataContext =新MainViewModel();
}

这应该工作。


I am creating a simple WPFapplication for implementing Databinding a Datagrid to database using Observable collection (following MVVM pattern).

App.xaml.cs class

public partial class App : Application
 {
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        var mainWindow = new MainWindow();
        var viewModel = new MainViewModel();
        mainWindow.Show();
    }
}

when I try to bind it to my XAML I have the following error raised :

Cannnot create an instance of "MainViewModel"

XAML code :

  <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">
    <!-- The error is raised here -->
   <Window.DataContext> 
     <ViewModel:MainViewModel/> 
   </Window.DataContext>

how to overcome this error ? Thanks.

P.S : I have posted the same question on MSDN forums but with my entire code, kindly have a look for better understanding.

On user's suggestion, do I have to keep my OnStartup() in this way ?

 public partial class App : Application
 {
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
    }
}

解决方案

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 ..

这篇关于无法创建&QUOT实例; MainViewModel&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆