You can perform one of the following solutions:
1) Use the Messenger template:
You can use the Messenger template if you use MVVMLight , for example, you can do the following:
In ViewModel do:
MyViewModel { private int _id; public int ID { get { return _id; } set { _id= value; OnPropertyChanged("_id"); } } Public void InitilizeMessenger() { Messenger.Default.Register(this,"To MyViewModel", (int id) => ID = id); } public MyViewModel() { InitilizeMessenger(); } }
You make ViewModel ready to receive messages by registering with Messenger.
in the do view:
MyView { MyView(int id) { InitializeComponent(); Messenger.Default.Send<int>(id,"To MyViewModel"); } }
Send the message by sending it along with the "To MyViewModel" tag so that it can be caught using MyViewModel.
2) Access to the DataContext from the view:
MyView { MyView(int id) { InitializeComponent(); ((MyViewModel)this.DataContext).ID = id; } }
The second solution is simple and simple, I gave the first option only for more complex scenarios.
source share