在WPF MVVM中动态添加控件

spi*_*een 20 wpf mvvm-light

我正在开发一个动态搜索视图,其中单击一个按钮应该添加一个包含3个组合框和2个文本框的新行.

我应该怎么做呢?

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)

你现在看到了所有你SearchEntryViewmodelsItemsControl(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最简单的方法.