There is a collection of objects that represent the data. There is a class that is a collection of xaml markup elements. Depending on the number of objects in the data collection, an appropriately sized array of markup objects is created. It is necessary to make a bidirectional connection between them. For example. Data:

public class SampleData { public string Name { get; set; } public int Count { get; set; } } 

Markup:

 class CountBlock : StackPanel { TextBlock tbName; TextBlock tbCount; Button btn; } 
  • Do you use MVVM ? - MihailPw
  • Uh ... CountBlock you give all the code for the CountBlock class? This will not work. And why do you want to link the elements in the code-behind? I hope not because you do not know how differently? - VladD
  • No, this is not all the code, there is still a constructor. I just didn’t want to clutter up with unnecessary details, I need to understand the basic essence of how to connect data fields with TextBlock. I want to link in the code-behind, because the number of elements is not known in advance, it will be determined dynamically during execution. If this can somehow be done right in xaml, then I really do not know how. - denny7794
  • @ denny7794: And what about the constructor? Give the whole class CountBlock , without it is not clear. - VladD

1 answer 1

I think you need not to reinvent the wheel, but to use existing means.

To bind to a dynamic collection (this is your ObservableCollection<SampleData> , right?), It's best to use an ItemsControl . And to set how each item looks, use the ItemTemplate . It turns out something like this:

 <ItemsControl ItemsSource="{Binding Тут-ваша-коллекция}"> <ItemsControl.ItemTemplate> <DataTemplate> <StackPanel> <TextBlock Text="{Binding Name}"/> <TextBlock Text="{Binding Count}"/> <Button Command="{Binding Тут-команда-вызываемая-по-нажатию}"/> </StackPanel> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> 

At the same time, there is no need for the CountBlock class.

  • I need CountBlock, because the markup is generated dynamically depending on the number of data elements, and these blocks are spread out along different Column and Row on the page, the number of which is also calculated dynamically, so that everything looks proportional. - denny7794
  • @ denny7794: If you want to arrange in rows / columns, then set as a ItemsPanel for example a UniformGrid , like here . - VladD