问题
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);
}
}
回答1:
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 ..
回答2:
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();
}
}
来源:https://stackoverflow.com/questions/14277497/cannot-create-an-instance-of-mainviewmodel