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”最终都会是一个 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 或对这种情况有用的控件吗?

谢谢你。

4

1 回答 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包含一个标签和一个文本框的代码段。CustonPropertyCustomProperties

于 2011-09-14T05:13:18.337 回答