按照MVVM模式动态创建控件

3

我希望在我的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”最终会成为一个文本框、复选框或组合框:
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速度?

  • 我能否以编程方式定义数据注释?例如,在解析自定义属性后,我能否向属性添加一些数据注释(Display、Validation),并将其绑定到DataForm、PropertyGrid或适用于此情况的有用控件?

谢谢。


1
关于第一个问题,请查看我在这里的回答。虽然是WPF而不是Silverlight,但很有可能您可以直接应用它。 - Jon
@Jon:谢谢你提供的链接。我明天会尝试实现它。使用数据模板时,是否也可以更新数据(类似双向绑定)? - Kamyar
当然可以,这只是一种更灵活的为对象指定可视树的方式。您可以执行与硬编码相同的操作。 - Jon
1个回答

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 的标签和文本框。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接