I have an application that opens a view that allows you to search for data. However, in order to to search, the user has to select what category he wants to search under. Currently, I'm trying to figure out how to pass that selected category from the main viewmodel(as an int) to the new search view's view model. Currently I'm trying to use something like this in the main view:
Let's say I have two views View1 and View2 an respective viewmodels for each. View2ViewlModel looks like this:
public class View2ViewlModel : ViewModelBase
{
private IDataService _dataService;
public int DivisionIdnt {get; set;}
public View2ViewModel(IDataService dataService)
{
_dataService = dataService;
}
}
And inside View1 we create and open View2 when a message is received.
public View2()
{
InitializeComponent();
Messenger.Default.Register<NotificationMessage<int>>(this, (m) => NotificationMesageReceived(m, m.Content));
}
private void NotificationMesageReceived(NotificationMessage<int> msg, int divisionIdnt)
{
if (msg.Notification == "SearchCred")
{
var findCredentialView = new View2();
findCredentialView.ShowDialog();
}
}
The message get's passed in View1ViewModel as part as an action that happens when the user clicks a search button. The problem is I want to initialize the DivisionIdnt property in the View2ViewModel for the new View2 to the value of divisionIdnt form the message. How can I achieve that? I thought about instantiating a View2ViewModel in code, setting DivisionIdnt to the message parameter and then setting the DataContext of the new View2to the newly created viewmodel, like this:
private void NotificationMesageReceived(NotificationMessage<int> msg, int divisionIdnt)
{
if (msg.Notification == "SearchCred")
{
var findCredentialView = new View2();
var vm = new View2ViewModel();
vm.DivisionIdnt = divisionIdnt;
findCredentialView.DataContext = vm;
findCredentialView.ShowDialog();
}
}
However, that doesn't work because in View2ViewModel, the constructor has an IDataService injected by DI at runtime.