1

I create a form in run-time from some parameters in a list of fields.

List<Fields>  lstFields =  new List<Fields>()
            {
                new Fields(){ FieldType = Fields.fieldTypes.INPUT, Info = "Some Info", Label = "first", Mandatory= true},
                new Fields(){ FieldType = Fields.fieldTypes.CHK, Info ="Some Info", Label="Second", 
                    Items = new List<String>(){"item1","item2","item3","item4"} },
                new Fields(){ FieldType = Fields.fieldTypes.INPUT, Label = "Name", Mandatory= true},
                new Fields(){ FieldType = Fields.fieldTypes.INPUT, Label = "Surname", Mandatory= true},
                new Fields(){ FieldType = Fields.fieldTypes.COMBO, Label = "City", Mandatory = false,  
                    Items = new List<String>(){"item1","item2","item3","item4"}}
            }

I create my fields in a foreach statement:

 foreach (Fields fd in lstFields)
                {

                    [...]
                    switch (fd.FieldType)
                    {

                        case Fields.fieldTypes.INPUT:
                            TextBox currentTB = new TextBox(); //It violates MVVM pattern :(
                            content.Add(currentTB);
                            [...]
                            break;
                        [...]
                        default:
                            break;
                    }
                }
            }

I need a form validation strategy. All the strategies that I know are based on the binding. The problem is that I can not bind the property because I create the controls dinamically. I would like to solve the problem following the MVVM design pattern.

overcomer
  • 2,244
  • 3
  • 26
  • 39

1 Answers1

2

You say you want to solve it using MVVM yet you're flagrantly violating it already by creating view elements in code. What you should be doing is creating view models to represent the GUI items you want to create, displaying them in an ItemsControl and using a combination of DataTemplates and Triggers to automatically create the view controls for you. By doing that you ensure that everything is data bound and that you adhere properly to MVVM; data validation is then done as it is in any other MVVM app.

As it turns out I answered a question just the other day and posted code showing exactly how to do this.

Community
  • 1
  • 1
Mark Feldman
  • 15,731
  • 3
  • 31
  • 58