2011-09-11 27 views
3

我想在我的Silverlight应用程序中动态生成一些控件。
更清楚,这是我班的简化定义:动态创建MVVM模式下的控件

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的”将最终成为一个文本框,复选框或组合框:

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或这种情况的有用控件?

谢谢。

+1

对于第一个问题,请参阅我的答案[这里](http://stackoverflow.com/questions/5267905/wpf-mvvm-creating-dynamic-controls/5267964#5267964)。它是WPF而不是Silverlight,但很有可能你可以逐字应用它。 – Jon

+0

@Jon:感谢您的链接。我会尽力明天实施。是否可以使用数据模板更新数据(类似于双向绑定)? – Kamyar

+0

当然,它只是为对象指定可视化树的更灵活的方式。如果你有硬编码,你可以做同样的事情。 – Jon

回答

3

在这些情况下,您通常使用直接从ItemsControl(例如ListBox)或ItemsControl继承的控件之一。从ItemsControl继承的控件允许您为集合中的每个项目定义模板,例如使用您的样品(假定你有通过视图模型访问您TestClass):

<ListBox ItemsSource="{Binding TestClass.CustomProperties }"> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="HorizontalContentAlignment" Value="Stretch"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
    <ListBox.ItemTemplate> 
     <DataTemplate> 
      <!--DataContext is stet to item in the ItemsSource (of type CustomProperty)--> 
      <StackPanel> 
       <TextBlock Text="{Binding DisplayName}"/> 
       <TextBox Text="{Binding Value}"/> 
      </StackPanel> 
     </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox> 

这段代码创建了一个ListBox包含一个标签,并在您的收藏CustomProperties每个CustonProperty文本框。