Reputation: 562
How do create controls dynamically in the mvvm pattern?
The code I'm trying to port:
Parent control:
ObservableCollection History = new ObservableCollection();
private void Save_Click(object sender, RoutedEventArgs e) { ChildControl cc = new ChildControl(); History.Add(cc); }
Upvotes: 1
Views: 581
Reputation: 4052
Assuming that "ChildControl" derives from UserControl, the XAML from each of these controls will be automatically displayed when the ItemsSource is set.
<ListBox ItemsSource="{Binding History}">
</ListBox>
Upvotes: 0
Reputation: 7719
if you use ContentControl, you can simply bind to your History collection
<ListBox ItemsSource="{Binding History}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<ContentControl Content="{Binding }"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The above will show a list of your controls.
One thing to consider though is that with your implementation, the VM knows about View Objects, It is cleaner to use pure data in your VM and have the view worry about how to display itself.
Upvotes: 0