I have a WPF application with Caliburn.Micro. The main ViewModel is ShellViewModel. It contains a tab control, and each tab contains a user control. I need to access a property of ShellViewModel from that internal user control.
var par = ((MyApp.ShellViewModel)((Screen)Parent).MyProperty;
ShellViewModel is not known though. Could you please tell how I can access it?
Thanks.
Ok from your comments it sounds like you have a combobox on the shell which needs to affect what is displayed on one of the tabs.
To communicate between your ViewModels, you can always use the
EventAggregatorwhich is part of CM and implements a subscriber pattern which you can take advantage ofe.g.
On your shell VM you can create a static instance of the aggregator or create a separate static class which will provide the aggregator to the application
You handle the
SelectionChangedof the combobox by using a standard action message or convention (I’m not sure what conventions CM applies by default to the combo so I’ll show the explicit bindings in my example)Hopefully if the correct conventions are applied, you should get the selected item being passed to the method
Your child VM just needs to subscribe to the aggregator and implement IHandle where T is the type of message it should handle
The
SelectionChangedMessagecan just be:Obviously the above could be a generic type so that you strongly type the
NewValueparameter – then again the message you publish can be anything, so it’s up to youIt might be worth pointing out that you can
Unsubscribefrom the aggregator so you can control when it receives notifications. The aggregator uses weak references anyway so you don’t need to worry too much about unsubscribing, but it does mean you have control over when your objects receive messages (i.e. stop listening when the are not active by subscribing onOnActivateand unsubscribing onOnDeactivate).