views:

353

answers:

1

Hello,

I have a UserControl with 5 small UserControl which are parts of the first UserControl.

The first UserControl is datatemplated by a MainViewModel type.

The other 5 small UserControls have also set the DataContext to this MainViewModel type.

Now I want additionally that those 5 UserControls get a 2nd DataContext to access other public

properties of another ViewModel .

How can I do that?

+1  A: 

I don't believe that you can have multiple DataContexts set for any given control.

So, depending on what exactly you're looking to do, you could:

a) Just set the DataContext for the 5 sub controls to the 2nd DataContext type

or

b) Create another ViewModel that inherits from your MainViewModel and also includes all the extra properties you need for the 5 sub controls. This would be in the case where you require everything from the MainViewModel AND the 2nd view model.

I guess you could also modify your main ViewModel to access properties on a subviewmodel, but this is all quite speculative without knowing what you're actually aiming to do.

Hope that helps :)

randomsequence
yes I have thought so because when I use datacontext the other/first is always overwritten/not used...I am doing a Master-Detail view with many aggregated ViewModels.My 5 small usercontrols need also data from public properties in the MainViewModel.
msfanboy
well inheriting from the MainViewModel for all sub viewmodels is actually no good idea.But I have just read about Prism and the regions feature. Do you know prism could that help me?
msfanboy
I just tried to inherit all from the MainViewModel and removed the code from the MainVM`s Ctor to a InitData method as I got errors. After that the app run, then I set the datacontext of all 5 views to each xxViewModel of them. Now the binding does not work anymore and I get no binding erros LOLIs it already time to trash the whole MVVM ?? It starts to really piss me off!
msfanboy
Hmm, I know what you mean, MVVM can feel very frustrating at times. But it is definitely helpful in organising and maintaining a large project.Sounds like you're not finding the xxViewModels - can you post your binding expressions in the main question? Don't forget that your subcontrols will have the MainViewModel already set as a DataContext, so if your MainViewModel exposes the xxViewModels as properties you can just bind like so: {Binding Path=xxViewModel} Again, this may not helpful, it's very hard to know. You may get more help if you put up some code!
randomsequence
forget it, I reverted the code ;-)
msfanboy