Dynamically Creating Controls Following MVVM pattern

那年仲夏 提交于 2019-12-04 14:39:49

In these cases you usualy use one of the controls inheriting from ItemsControl (e.g. ListBox) or the ItemsControl directly. The controls inheriting from ItemsControl allow you to define a template for each item in a collection, e.g. using your sample (assuming you got access to your TestClass through a view model):

<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>

This snippet creates a ListBox that contains a label and a text box for each CustonProperty in your CustomProperties collection.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!