现在有这么一个需求,需要动态添加自定义控件到界面,自定义控件数量不固定,内容是通过服务获取的,以前是做winform的,winform简单,直接 new自定义控件添加上去就行,现在wpf mvvm模式,不知道怎么做了,能否在viewmodel中添加一个 observablecollection,界面绑定这个属性,界面自动生成这么多个自定义控件?如果可以,各位大佬能否提供下实现思路,有个demo什 么的最好了。
<Window x:Class="WpfApplication5.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Window.Resources>
<!--控件模板-->
<DataTemplate x:Key="UserDataTemplate">
<Border BorderThickness="2" BorderBrush="Black" Margin="2">
<StackPanel>
<Image />
<Label HorizontalAlignment="Center" Content="{Binding Path=Name}" />
</StackPanel>
</Border>
</DataTemplate>
</Window.Resources>
<Grid Name="mygrid">
<!--容器-->
<ItemsControl x:Name="testList" ItemTemplate="{StaticResource UserDataTemplate}" ItemsSource="{Binding Btns}">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientatio