在WPF MVVM中动态添加控件 [英] Adding controls dynamically in WPF MVVM

查看:1267
本文介绍了在WPF MVVM中动态添加控件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a dynamic search view wherein clicking a button should add a new row containing 3 combobox and 2 textboxes.

我应该怎么做?

推荐答案

如果您确实想执行mvvm,请尝试忘记如何添加控件".您不需要,只需考虑一下您的视图模型-WPF为您创建控件:)

If you really want to do mvvm , try to forget "how can I add controls". You don't have to, just think about your viewmodels - WPF create the contols for you :)

就您而言,假设我们有一个SearchViewModel和SearchEntryViewmodel.

In your case lets say we have a SearchViewModel and a 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绑定到MySearchItems.

Till now you dont have to think about usercontrols/view. In your SearchView you create an ItemsControl and bind the ItemsSource to MySearchItems.

<ItemsControl ItemsSource="{Binding MySearchItems}"/> 

您现在可以在ItemsControl(just the ToString() atm)中看到所有SearchEntryViewmodels.

You see now all of your SearchEntryViewmodels in the ItemsControl(just the ToString() atm).

要满足您的要求以显示每个带有3个组合框的SearchEntryView模型,依此类推,您只需在资源"中定义一个DataTemplate

To fit your requirements to show every SearchEntryViewmodel with 3Comboboxes and so on you just have to define a DataTemplate in your Resources

<DataTemplate DataType="{x:Type local:SearchEntryViewmodel}">
    <StackPanel Orientation="Horizontal">
        <Combobox ItemsSource="{Binding MyPropertyInSearchEntryViewmodel}"/>
        <!-- the other controls with bindings -->
    </StackPanel>
</DataTemplate>

仅此而已:),您无需考虑如何动态添加控件?".您只需要向收藏夹添加新的SearchEntryViewmodel.

That's all :) and you never have to think about "how can I add controls dynamically?". You just have to add new SearchEntryViewmodel to your collection.

这种方法称为 Viewmodel First ,我认为这是制作MVVM的最简单方法.

This approach is called Viewmodel First and I think it's the easiest way to do MVVM.

这篇关于在WPF MVVM中动态添加控件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆