0

I need to create a childwindow that should contain the controls according to the model passed to it. For Example, If a model contains 5 properties (it can contain any number of properties), 2 of type string, 1 datetime and 2 lists, it should create 2 textboxes with labels as property name, 1 Datepicker with lable as property name, and 2 comboboxes with label as property name. Basically, controls should be created dynamically according to properties along with the Label as name of the property. I am following MVVM. Any help will be appreciated. Thanks.

1 Answer 1

1

Get the list of PropertyInfos of your model and wrap them in ViewModels. Then use DataTemplates with implicit keys to generate your controls.

Step1: Get PropertyInfoViewModels

var vms = model.GetType().GetAllProperties.Select(p=> ViewModelFactory.Create(p));

Your factory should return a StringPropertyViewModel for string properties, etc.

abstract class PropertyViewModel<T> : INotifyPropertyChanged
{
   public string Caption {get; set;}
   public T Value {get; set;}
}

Step2: DataTemplates

<DataTemplate TargetType="{x:Type sys:StringPropertyViewModel}">
   <StackPanel Orientation="Horizontal">
    <Label Text="{Binding Caption}" />
    <TextBox Text="{Binding Value}" />
   </StackPanel>
</DataTemplate>

Step3: Ensure the DataTemplates are in the Resources section of your Window or can be resolved via a ResourceDictionary.

Step4: In the window ViewModel, expose the generated PropertyViewModels

<Window...>
...
   <ItemsControl ItemsSource="{Binding ModelPropertyViewModels}">
    <ItemsControl.Resources>
     <!-- This might be a good place to post your DataTemplates --->
    <ItemsControl.Resources>
   </ItemsControl>

...
</Window>
Sign up to request clarification or add additional context in comments.

2 Comments

What I have done so far is created a ViewModel that contains a list of properties along with the type and value. Now I need to plug it to View. I am not sure what control to use. I have written a TemplateSelector Class that selects the template based on the type of the property. Only thing left is what control to use to display my window.
Normally I'd use an ItemsControls with the ItemsSource set to {Binding MyListOfProperties}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.