I am at a loss over something that is probably incredibly simple.
I did search but faield to find an exact answer that i needed.
The problem is as followed.
I am teaching myself silverlight MVVM.
Currently I’m writing an application that uses 1 mainpage and 2 usercontrolls.
As you can imagine, 3 viewmodels.
Currently in my XAML:
mainpage.xaml
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:vm="clr-namespace:newFileupload.ViewModel"
xmlns:vw="clr-namespace:newFileupload.View"
<UserControl.DataContext>
<vm:MainPageViewModel />
</UserControl.DataContext>
<Grid x:Name="LayoutRoot" Background="White">
<vw:PicturesOverviewView />
</Grid>
PicturesOverviewView.xaml
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"
<Grid x:Name="LayoutRoot" Background="White">
</Grid>
So in mainpage.xaml, I set the datacontext in xaml, i then call the usercontrol in the grid like so:
<vw:PicturesOverviewView />
This gives me the following error:
Error 1 Cannot create an instance of "PicturesOverviewView". C:\Programming\C#\newFileUpload\newFileupload\MainPage.xaml 16 9 newFileupload
I have absolutely no clue what is causing this, and secondly..
How do I bind view models to the appropriate usercontrol?
Do I need to declare the view namespace for every usercontrol and then set its datacontext like the mainpage?
Thanks for taking the time to read and I hope to be able to continue soon 🙂
If the code shown is correct, you are attempting to create a PicturesOverviewView control inside a PicturesOverviewView control. That will account for the compile error. (I am guessing though that you have cut & Paste the same Xaml twice).
Binding-wise:
You want to bind the child controls to properties on the main view Model, that are themselves view models
e.g.
Then the MainPage binds like this:
Something somewhere needs to create your view models with the right data. It makes sense to hangs the children off the parent viewmodel.
I would suggest you look at using IOC injection (e.g. using Unity) as it sounds like you may simply wish to create singletons referenced at various levels. The issue is where do you want to provide re-use as if you hard-wire data contexts in the child views you cannot reuse them.