How to view a constructor parameter to view a model

I have a View and a ViewModel.

MyView { MyView(int id) { InitializeComponent(); } } MyViewModel { private int _id; public int ID { get { return _id; } set { _id= value; OnPropertyChanged("_id"); } } } 

I set the Context data on my XAML as:

 <Window.DataContext> <vm:MyViewModel/> </Window.DataContext> 

When I click the button, I show my view as:

 Application.Current.Dispatcher.Invoke(() => new MyView(id).Show()); 

Now, how to pass the identifier from MyView(id) to MyViewModel.ID.

+5
source share
3 answers

Since the DataContext is created after calling InitializeComponent (), you can simply pass it to the ViewModel:

 MyView { MyView(int id) { InitializeComponent(); ((MyViewModel)DataContext).ID = id; } } 
+4
source

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.

+4
source

First, OnPropertyChanged ("_ id") is erroneous, beacuse _id is a variable, not a property. You must change it as OnPropertyChanged ("ID"). You can assign viewModel in code.

 class MyView { MyView(int id) :this(new MyViewModel(id)) { } MyView(MyViewModel viewModel) { InitializeComponent(); this.DataContext = viewModel; } } class MyViewModel { private int _id; public int ID { get { return _id; } set { _id= value; OnPropertyChanged("ID"); } } public MyViewModel(int id) { ID=id; } } 
+1
source

All Articles