Reputation: 4685
Is there a way to pass a complex type as a parameter into a method. I would like to implement a more generic method listed below.
I would like to pass View (class) name into the method, instead of explicitly specifying 'ParticipantSummaryView'
in teh case below. Thanks
private void InitializePdfView(ParticipantBasic selectedParticipant,
string regionName, string viewName)
{
IRegion region = this.regionManager.Regions[regionName];
if (region == null) return;
// Check to see if we need to create an instance of the view.
var view = region.GetView(viewName) as ParticipantSummaryView;
if (view == null)
{
// Create a new instance of the EmployeeDetailsView using the Unity container.
view = this.container.Resolve<ParticipantSummaryView>();
// Add the view to the main region. This automatically activates the view too.
region.Add(view, viewName);
}
else
{
// The view has already been added to the region so just activate it.
region.Activate(view);
}
// Set the current employee property on the view model.
var viewModel = view.DataContext as ParticipantSummaryViewModel;
if (viewModel != null)
{
viewModel.CurrentParticipant = selectedParticipant;
}
}
Upvotes: 0
Views: 132
Reputation: 77285
You can use generics:
private void InitializePdfView<TView, TViewModel>(ParticipantBasic selectedParticipant, string regionName, string viewName)
{
IRegion region = this.regionManager.Regions[regionName];
if (region == null) return;
// Check to see if we need to create an instance of the view.
var view = region.GetView(viewName) as TView;
if (view == null)
{
// Create a new instance of the EmployeeDetailsView using the Unity container.
view = this.container.Resolve<TView>();
// Add the view to the main region. This automatically activates the view too.
region.Add(view, viewName);
}
else
{
// The view has already been added to the region so just activate it.
region.Activate(view);
}
// Set the current employee property on the view model.
var viewModel = view.DataContext as TViewModel;
if (viewModel != null)
{
viewModel.CurrentParticipant = selectedParticipant;
}
}
However, you will need to implement a constraint for your TViewModel
because calling .CurrentParticipant
on any type is not possible. You will need to make the viewModel
variable dynamic
or use a proper interface or base class for the viewmodel that has such a method.
Calling this could look like:
InitializePdfView<ParticipantSummaryView, ParticipantSummaryViewModel>(selectedParticipant, regionName, viewName);
Upvotes: 1