简体   繁体   中英

WPF/MVVM:Set multiple datacontext to ONE usercontrol

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?

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM