Search code examples
silverlighttemplatesmvvmchildwindow

MVVM Pattern in a templated form


In my silverlight application the user can create multiple templates of a form. Depending upon the template selected, the form would display a set of views in a particular order. Furthermore, some of the views are "required" if present on the template. The client wants such views to be displayed in a popup form so the user focuses on just those "required" views first before moving onto the other views on the form.

Now, I see myself breaking MVVM pattern for this requirement. Here's why... 1. The ViewModel can read the template from the db, grab the views (using MEF) but to add them to the form, it would need to know the name of the layout grid and add views as a child to that grid. Thats like telling the ViewModel about the UI elements which is against MVVM design pattern.

  1. For the "required" views that must be displayed in a popup, the viewModel would need to create a ChildWindow instance, add the "required" views to it and then show the Childwindow. Also handles Closed/closing events.

I am sure my approach is flawed but am not able to figure out a way to cleanly separate the UI logic from the business logic here. Can someone provide a better approach.

Thanks. A


Solution

  • Here's on solution that comes to my mind.

    1.Decorate ViewModels with metatags that carry the View name the ViewModel is associated with.

    1. Create a new Class called ViewViewModel that holds two properties

      • View Name
      • ViewModel instance.
    2. On the Form ViewModel, which is responsible for aggregating all the Views together and also bring up a childwindow depending upon the case. Add three properties

      • List FormViews
      • List ChildWindowViews.
      • Action ShowChildWindow

    The FormView Model will instantiate required viewmodels, gather the View name from each viewmodel from its MEF metatag and populate the FormView and ChildWindowView properties. Once the Form ViewModel is done processing the request and the two properties have been populated it fires the ShowWindow delegate with true parameter if ChildWindow is not empty.

    1. Form View will do the following

      • The Layout root will have a stackpanel bound to the FormView property. There will be an IValueConverter that processes each entry in FormViews List. For each ViewName, it finds and creates intance of the view. Sets the DataContext to the ViewModel.

      • When the ShowChildWindow action is raised, there's minimal code-behind in Form View that it creates and shows a ChildWindow that is bound to the ChildWindowViews property. ChildWindow property uses the same IValueCOnverter to create instances of requested Views.

    How does that sound? Pls comment

    enter code here