遵循 MVVM 模式动态创建控件
我想在我的 silverlight 应用程序中动态生成一些控件。
更清楚地说,这是我的类的简化定义:
public class TestClass
{
[Display(Name="First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public List<CustomProperty> CustomProperties { get; set; }
}
每个“CustomProperty”最终将是一个 TextBox、CheckBox 或 ComboBox:
public class CustomProperty
{
public CustomDataType DataType { get; set; } //enum:integer, string, datetime, etc
public object Value { get; set; }
public string DisplayName { get; set; }
public string Mappings { get; set; } // Simulating enums' behavior.
}
使用 MVVM 模式实现此功能的最佳方法是什么?如果我解析 ViewModel 中的 CustomProperties,并找出应创建哪些控件,如何基于 MVVM 模式在视图中创建新控件。
是否有任何 silverlight 控件可以帮助我使 UI 更快?
我可以通过编程方式定义数据注释吗?例如,在解析自定义属性之后,我可以向该属性添加一些数据注释(显示、验证)并将其绑定到 DataForm、PropertyGrid 或针对这种情况的有用控件吗?
谢谢。
I'd like to dynamically generate some controls in my silverlight application.
To be more clear, here's a simplified definition of my class:
public class TestClass
{
[Display(Name="First Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public List<CustomProperty> CustomProperties { get; set; }
}
Each "CustomProperty" will finally be a TextBox, CheckBox or ComboBox:
public class CustomProperty
{
public CustomDataType DataType { get; set; } //enum:integer, string, datetime, etc
public object Value { get; set; }
public string DisplayName { get; set; }
public string Mappings { get; set; } // Simulating enums' behavior.
}
What is the best way to implement this using MVVM pattern? If I parse CustomProperties in ViewModel, and find out which controls should be created, How can I create new controls in my view based on MVVM pattern.
Is there any silverlight control that can help me make the UI faster?
Can I define data annotations programmatically? for example after parsing the custom property, can I add some data annotations (Display, Validation) to the property and bind it to a DataForm, PropertyGrid or a useful control for this situation?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这些情况下,您通常使用继承自
ItemsControl
的控件之一(例如ListBox
)或直接使用ItemsControl
。继承自ItemsControl
的控件允许您为集合中的每个项目定义一个模板,例如使用示例(假设您通过视图模型访问TestClass
):此代码段创建一个
ListBox
,其中包含CustomProperties
集合中每个CustonProperty
的标签和文本框。In these cases you usualy use one of the controls inheriting from
ItemsControl
(e.g.ListBox
) or theItemsControl
directly. The controls inheriting fromItemsControl
allow you to define a template for each item in a collection, e.g. using your sample (assuming you got access to yourTestClass
through a view model):This snippet creates a
ListBox
that contains a label and a text box for eachCustonProperty
in yourCustomProperties
collection.