问题描述
我创建实现使用观察的集合(以下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:我已经张贴上的但我的整个代码,请看看为了更好的理解。
在用户的建议,我必须保持我的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 ..
这篇关于无法创建"实例; MainViewModel"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!