你UserControls应该有一个 ViewModel (让我们ItemViewModel现在调用它)。
您的 MainViewModel 应该有一个ObservableCollection<ItemViewModel>.
然后,您的视图应该有一个ItemsControl(或其派生类之一,例如ListBox),其ItemsSource属性将绑定到ObservableCollection. 然后ItemsControl应该定义一个ItemTemplate包含你的UserControl.
这是使用 WPF / MVVM 进行描述的正确方法。
示例(伪代码):
主视图模型:
public class MainViewModel
{
public ObservableCollection<ItemViewModel> Items {get;set;}
}
主视图:
<Window>
<ItemsControl ItemsSource="{Binding Items}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<my:UserControl/>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</Window>
请记住,每个实例UserControl都会将其DataContext设置为源集合中的相应项。
因此,如果您的 ItemsViewModel 看起来像这样:
public class ItemsViewModel
{
public string LastName {get;set;}
public string FirstName {get;set;}
//INotifyPropertyChanged, etc.
}
你UserControl可以这样定义:
<UserControl>
<StackPanel>
<TextBox Text="{Binding LastName}"/>
<TextBox Text="{Binding FirstName}"/>
</StackPanel>
</UserControl>