Reputation: 41
I have problem passing object to secondary view in MVVM light WPF. I have main view Model. follow of operation. I am able to wire things up using MVVM light and Modren UI navigation Services. The issue is that i am not able to send object of Main Customer view model to secondary View Model. I want to set data-context of target View from source View Model. I have tried this but does not seem to be working. I prefer no code behind and i have spent a lot of time without any success.
public virtual void NavigateTo(string pageKey, object parameter)
{
lock (_pagesByKey)
{
if (!_pagesByKey.ContainsKey(pageKey))
{
throw new ArgumentException(string.Format("No such page: {0}. Did you forget to call NavigationService.Configure?", pageKey), "pageKey");
}
var frame = GetDescendantFromName(Application.Current.MainWindow, "ContentFrame") as ModernFrame;
// Set the frame source, which initiates navigation
if (frame != null)
{
frame.Source = _pagesByKey[pageKey];
//i Dont know if this should work or not
frame.DataContext = parameter;
}
Parameter = parameter;
_historic.Add(pageKey);
CurrentPageKey = pageKey;
}
}
any help will be greatly appreciated. I just need to how i can set the datacontext of target View without using code behind. Thanks
Upvotes: 1
Views: 262
Reputation: 8404
There's multiple possibilities but one that does not create dependencies between your viewmodels is to use pub/sub system in MVVMLight. Basically it goes like this:
When you select some entity from your view and transition to another, viewmodel sends a message that carriers that given entity along. In the other viewmodel you receive the message and set some property accordingly (for editing, adding new entity, etc.)
// mainviewmodel
Messenger.Default.Send(new MyMessage(myObj));
// otherviewmodel
Messenger.Default.Register<MyMessage>(this, message =>
{
/* do something with message.MyObj */
});
// mymessage
public class MyMessage : MessageBase
{
...
public MyObj MyObj { get; set; }
}
Upvotes: 1