如果您真的想做 mvvm ,请尝试忘记“如何添加控件”。您不必这样做,只需考虑您的视图模型 - WPF 会为您创建控件:)
在您的情况下,假设我们有一个 SearchViewModel 和一个 SearchEntryViewmodel。
public class SearchEntryViewmodel
{
//Properties for Binding to Combobox and Textbox goes here
}
public class SearchViewModel
{
public ObservableCollection<SearchEntryViewmodel> MySearchItems {get;set;}
public ICommand AddSearchItem {get;}
}
到目前为止,您不必考虑用户控件/视图。在你的SearchView
你创建一个ItemsControl
并绑定ItemsSource
to MySearchItems
.
<ItemsControl ItemsSource="{Binding MySearchItems}"/>
你现在看到你所有的SearchEntryViewmodels
in the ItemsControl(just the ToString() atm)
.
为了满足您的要求,显示带有 3Comboboxes 的每个 SearchEntryViewmodel 等,您只需在资源中定义一个 DataTemplate
<DataTemplate DataType="{x:Type local:SearchEntryViewmodel}">
<StackPanel Orientation="Horizontal">
<Combobox ItemsSource="{Binding MyPropertyInSearchEntryViewmodel}"/>
<!-- the other controls with bindings -->
</StackPanel>
</DataTemplate>
这就是全部:),您永远不必考虑“如何动态添加控件?”。你只需要添加新的SearchEntryViewmodel
到你的收藏。
这种方法称为首先查看模型我认为这是实现 MVVM 最简单的方法。