I need to create 40 text fields with labels, can I somehow do without copy-paste, and just create a template? I read about it on the Internet, but did not understand until the end. Each bundle (TextBox and Label) is wrapped in a StackPanel:

<StackPanel MinWidth="180" HorizontalAlignment="Stretch" Margin="5"> <Label Content="{DynamicResource "Название метки"}" Margin="0" Padding="0"></Label> <TextBox Padding="5" Text="{Binding "Здесь название свойства"}" Height="27" ></TextBox> </StackPanel> 

    2 answers 2

    There are two options for this:

    1. Create a UserControl and place the markup in it, and then use it 40 times.
    2. Create a DataTemplate with the necessary markup and then mark it with 40 ContentControls.
    • I wonder what is more convenient to work with in the code, if you generate these 40 interactively through the code on request from the UI? Or which option would you choose and why? - Bulson
    • @Bulson; Both variants are perfectly applied through the code. I would choose UserControl, because it requires less code (just to create), and for ContentControl, you also need to find a resource with DataTemplate and apply. - Kibnet Philosoff
    • @ Kibnet Philosoff thanks. - Bulson

    If you need to create many items besides the already mentioned UserControl and DataTemplate you might need an ItemsControl (especially if you are writing using MVVM).

    Your code will look like this:

     <ItemsControl ItemsSource="{Binding TextDescriptionCollection}"> <ItemsControl.ItemTemplate> <DataTemplate DataType="{x:Type vm:SingleTextDescriptionVM}"> <StackPanel MinWidth="180" HorizontalAlignment="Stretch" Margin="5"> <Label Content="{Binding FieldName}" Margin="0" Padding="0"/> <TextBox Padding="5" Text="{Binding FieldValue}" Height="27" /> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> 

    You can change the element container if you need a non-vertical layout.