Another approach that does not violate the open / closed principle is to create view models and views for each type of StockItem, and then a type that compares all open subtypes and their corresponding view models and provides a factory that accepts the StockItem element and returns the corresponding view model.
This would be easy to do with an IoC or MEF container, for example.
Update
As a quick example using MEF:
public class StockItemEditViewModelFactory : IPartImportsSatisfiedNotification { private Dictionary<Type, IStockItemEditViewModelResolver> resolvers; [ImportMany(IStockItemEditViewModelResolver)] private IEnumerable<IStockItemEditViewModelResolver> importedResolvers; public void OnImportsSatisfied() {
This is not tested, but shows a general approach. You can use generics to make this tidier.
If you want to use Unity instead of MEF, then the concept will be the same, but you will need to register each implementation of IStockItemEditViewModelResolver (or use the Unity extension and do this with the conventions), and then your factory will need a reference to the container so that it can execute ResolveAll ( see Unity Resolve for several classes ).
source share