Reputation: 189
I have 2 Views the first one contain a list of users and the second where I can edit a user, all what I want is to pass the Id between the 2 ViewModel of each screen for I can know the user that will be modified. I'm a beginner working using the MVVM Light Framework, Can any one give me the best solution for this case ?
Upvotes: 1
Views: 1875
Reputation: 726
Instead of using the messenger (using the messenger to often tends to messy your code) i would suggest to pass the id with the "Edit User" button/action and then use the id in the constructor of your target viewmodel.
Button in your view:
<Button Content="Edit"
Command="{Binding DataContext.EditButtonCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=UserControl}}"
CommandParameter="{Binding }" />
In your viewmodel:
public ICommand EditButtonCommand= new RelayCommand<object>(UseEditButton)
private async void UseEditButton(object obj)
{
YourModel id = obj as YourModel;
YourEditViewModel viewModel = new YourEditViewModel(id)
//navigate to vm
}
Upvotes: 1
Reputation: 2200
First wrap your variable inside a class.
public class VariableMessage
{
public string YourVariable { get; set; }
}
Then to receive message register in the receiving view model initializer.
Messenger.Default.Register<VariableMessage>
(
this,
(action) => ReceiveVariableMessage(action)
);
private object ReceiveVariableMessage(VariableMessage variableMessage)
{
Console.WriteLine(variableMessage.YourVariable);
return null;
}
To send message
Messenger.Default.Send<VariableMessage>(new VariableMessage() { YourVariable = "Hello"});
Upvotes: 4