I'm using mvvm light to build a Silverlight application. Is there a code snippet that shows how to access a view model's property or command from within another view model or user control's code behind?
I guess it's simple, but I somehow missed something.
Ueli
Here, the Main View contains an instance of a Detail View. The Views' DataContexts are the MainViewModel and DetailViewModel respectively. To pass data from the Main View/Main ViewModel to the Detail ViewModel, assign the data to the ViewModelExtensions. Parameter attached property on the Detail View instance.
The other approach to bind the View and Viewmodel in View First Approach is in the xaml itself as shown in the figure below. I am setting the datacontext in the . xaml of the View itself. To set the datacontext in this way the ViewModel class need to have a default constructor.
MvvmCross has some setup code provided by the framework, and inside this setup code you initialize the content of the IoC container. MVVM Light, on the other hand, relies on you doing this inside your own app code.
You could use the Messenger to do this: Send the user in the UserViewModel:
Messenger.Send<User>(userInstance);
would just send the user to anyone interested.
And register a recipient in your CardViewModel:
Messenger.Register<User>(this, delegate(User curUser){_curUser = curUser;});
or you can also send a request from your CardViewModel for shouting the user:
Messenger.Send<String, UserViewModel>("Gimme user");
And react on that in the UserViewModel:
Messenger.Register<String>(this, delegate(String msg)
{
if(msg == "Gimme user")
Messenger.Send<User>(userInstance);
});
(You better use an enum and not a string in a real scenario :) )
Perhabs you can even response directly but I can't check it at the moment.
Just check this out: Mvvm light Messenger
Another way is to use the overload of RaisePropertyChanged that also broadcasts the change. You would do this:
RaisePropertyChanged(() => MyProperty, oldValue, newValue, true);
Then in the subscriber:
Messenger.Default.Register<PropertyChangedMessage<T>>(this, Handler);
where T is the type of MyProperty.
Cheers Laurent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With