简体   繁体   English

如何使用MVVM模式在WPF中创建动态表单?

[英]How to create dynamic forms in WPF using MVVM pattern?

I need to create a dynamic forms in WPF. 我需要在WPF中创建动态表单。 For example, say I need to allow the user to create a family tree with information about each of the people and each person will have infomation about their occupation. 例如,假设我需要允许用户创建包含有关每个人的信息的家谱,并且每个人都将拥有有关其职业的信息。

class Person
{
    int age;
    int dateOfBirth;
    List<Job> jobList = new List<Job>();
}

class Job
{
    string title;
    int salary;
}

This program needs to be able to have fields that will allow data entry of all the members in the class, including multiple jobs. 该程序必须能够具有允许类中所有成员(包括多个作业)的数据输入的字段。 I would like the forms data to (possibly) coded in XAML, where if they click the button "Add Person" it will expand another person entry box to allow the user to add information about the person. 我希望表单数据(可能)以XAML编码,如果他们单击按钮“添加人员”,它将展开另一个人员输入框,以允许用户添加有关人员的信息。 This is the same as "Add Job" but the jobs are only added under that person. 这与“添加作业”相同,但是作业仅在该人下添加。

(Note that the end result of this will be a tree data structure that contains all the people and their children) (请注意,这样做的最终结果将是一个包含所有人员及其子代的树数据结构)

How would I go about doing this in WPF using the MVVM pattern? 我将如何使用MVVM模式在WPF中执行此操作? Before I learned the MVVM pattern, I had used code behind and created dynamic view using c# to code the XAML view and added it dynamically as child elements. 在学习MVVM模式之前,我曾使用过代码,并使用c#创建了动态视图以对XAML视图进行编码并将其动态添加为子元素。 But I don't think that is the best way to do this since it seems too tedious. 但是我认为这不是最好的方法,因为它看起来太乏味了。

I'm new to the MVVM pattern so some small code snippets of how I would do this (using databinding?) would be very helpful. 我是MVVM模式的新手,所以一些有关如何执行此操作的小代码片段(使用数据绑定?)将非常有帮助。

I made a quick example coded in XAML of how the form might look like: 我用XAML编写了一个简短的示例,说明了表单的外观:

在此处输入图片说明

This problem is solved in WPF using DataTemplate s. 使用DataTemplate在WPF中解决了此问题。 In any place you need a "repeated" form, you will set up something like this: 在任何需要“重复”表格的地方,您都将设置以下内容:

<ItemsControl ItemsSource="{Binding Jobs}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <...>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

You use ListView to get a collection control, that will display a instance of the DataTemplate for every item in the bound collection. 您可以使用ListView获取一个集合控件,该控件将为绑定集合中的每个项目显示DataTemplate的实例。 Inside of the DataTemplate , your DataContext is the bound item inside the collection, ie. DataTemplate内部,您的DataContext是集合的绑定项,即。 an instance of the Job class. Job类的实例。

If Jobs was an ObservableCollection<T> then the control would automatically update when items were added or removed from the bound collection. 如果JobsObservableCollection<T>则在将项目添加到绑定集合中或从绑定集合中删除项目时,控件将自动更新。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM