我在运行时从字段列表中的一些参数创建了一个表单。
List<Fields> lstFields = new List<Fields>()
{
new Fields(){ FieldType = Fields.fieldTypes.INPUT, Info = "Some Info", Label = "first", Mandatory= true},
new Fields(){ FieldType = Fields.fieldTypes.CHK, Info ="Some Info", Label="Second",
Items = new List<String>(){"item1","item2","item3","item4"} },
new Fields(){ FieldType = Fields.fieldTypes.INPUT, Label = "Name", Mandatory= true},
new Fields(){ FieldType = Fields.fieldTypes.INPUT, Label = "Surname", Mandatory= true},
new Fields(){ FieldType = Fields.fieldTypes.COMBO, Label = "City", Mandatory = false,
Items = new List<String>(){"item1","item2","item3","item4"}}
}
我在 foreach 语句中创建我的字段:
foreach (Fields fd in lstFields)
{
[...]
switch (fd.FieldType)
{
case Fields.fieldTypes.INPUT:
TextBox currentTB = new TextBox(); //It violates MVVM pattern :(
content.Add(currentTB);
[...]
break;
[...]
default:
break;
}
}
}
我需要一个表单验证策略。我所知道的所有策略都是基于绑定(bind) .问题是我无法绑定(bind)属性,因为我动态地创建了控件。我想按照 MVVM 设计模式解决问题。
最佳答案
您说您想使用 MVVM 解决它,但您已经通过在代码中创建 View 元素公然违反它。您应该做的是创建 View 模型来表示您想要创建的 GUI 项,在 ItemsControl 中显示它们并使用 DataTemplates 和触发器的组合自动为您创建 View 控件。通过这样做,您可以确保所有内容都是数据绑定(bind)的并且您正确遵守 MVVM;然后像在任何其他 MVVM 应用程序中一样完成数据验证。
结果我前几天回答了一个问题并发布了code showing exactly how to do this .
关于c# - 在 WPF 中运行时创建的字段的表单验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32604953/