【问题标题】:Dynamically Creating Controls Following MVVM pattern按照 MVVM 模式动态创建控件
【发布时间】:2011-11-14 17:55:20
【问题描述】:

我想在我的 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 或对这种情况有用的控件吗?

谢谢。

【问题讨论】:

  • 第一个问题看我的回答here。它是 WPF 而不是 Silverlight,但您很有可能能够逐字应用它。
  • @Jon:感谢您的链接。明天我会尝试实施它。是否也可以使用数据模板更新数据(类似于双向绑定)?
  • 当然可以,它只是为对象指定可视化树的一种更灵活的方式。如果您对它进行硬编码,您可以做同样的事情。

标签: silverlight silverlight-4.0 mvvm mvvm-light dataform


【解决方案1】:

在这些情况下,您通常使用继承自 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>

此 sn-p 创建一个 ListBox,其中包含您的 CustomProperties 集合中每个 CustonProperty 的标签和文本框。

【讨论】:

    猜你喜欢
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    相关资源
    最近更新 更多