I have a set of views and view models in my project. There is a one-to-one mapping of views and view models, so each view requires a particular view model. I'd like to instantiate a series of views given a collection of view models.
Here's what I've come up with:
public class OverlayBundle : DrawingVisual
{
private static readonly Dictionary<Type, Func<IOverlayViewModel, DrawingVisual>> _overlayCreators =
new Dictionary<Type, Func<IOverlayViewModel, DrawingVisual>>
{
{ typeof(ImageOverlayViewModel), x => new ImageOverlay((ImageOverlayViewModel)x) },
{ typeof(ValuesOverlayViewModel), x => new ValuesOverlay((ValuesOverlayViewModel)x) },
{ typeof(NoGoAreasOverlayViewModel), x => new NoGoAreasOverlay((NoGoAreasOverlayViewModel)x) },
};
private readonly OverlayBundleViewModel _viewModel;
private IEnumerable<Visual> _overlays;
public OverlayBundle(OverlayBundleViewModel viewModel)
{
_viewModel = viewModel;
GenerateChildren();
}
private void GenerateChildren()
{
_overlays = _viewModel.GetAllOverlayViewModels().Select(GetOverlay);
foreach (var overlay in _overlays)
Children.Add(overlay);
}
private Visual GetOverlay(IOverlayViewModel viewModel)
{
return _overlayCreators[viewModel.GetType()](viewModel);
}
}
This works, but I feel like there must be a better way. Any feedback would be appreciated.