bli*_*eis 56
如果你真的想做mvvm,试着忘记"我该如何添加控件".你没必要,只考虑你的viewmodels - 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;}
}
Run Code Online (Sandbox Code Playgroud)
直到现在你不必考虑用户控制/视图.在SearchView
你的创建ItemsControl
和绑定ItemsSource
到你MySearchItems
.
<ItemsControl ItemsSource="{Binding MySearchItems}"/>
Run Code Online (Sandbox Code Playgroud)
你现在看到了所有你SearchEntryViewmodels
的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>
Run Code Online (Sandbox Code Playgroud)
这就是全部:)你永远不必考虑"如何动态添加控件?".您只需要SearchEntryViewmodel
为您的收藏添加新内容即可.
这种方法称为Viewmodel First,我认为这是做MVVM最简单的方法.