Reputation: 1
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.
Upvotes: 0
Views: 749
Reputation: 3764
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>
Upvotes: 1