如何在mvvm模式中动态创建控件?
我想要移植的代码:
家长控制:
ObservableCollection History = new ObservableCollection();
private void Save_Click(对象发送者,RoutedEventArgs e) { ChildControl cc = new ChildControl(); History.Add(CC); }
答案 0 :(得分:0)
如果您使用ContentControl,则只需绑定到History集合
即可<ListBox ItemsSource="{Binding History}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<ContentControl Content="{Binding }"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
以上将显示您的控件列表。
要考虑的一件事是,通过您的实现,VM了解View Objects,在VM中使用纯数据并让视图担心如何显示自己更加清晰。
答案 1 :(得分:0)
假设“ChildControl”派生自UserControl,则在设置ItemsSource时,将自动显示每个控件的XAML。
<ListBox ItemsSource="{Binding History}">
</ListBox>