Is it possible to repeat XAML blocks, foreach style?

I am making a WPF application consisting of a base map with several campsite overlaps.

The number of camping sites is dynamically updated in the collection, so I want to write XAML, which will create more camping images as needed.

But I am not familiar with any construct foreachor other repetitive code in XAML.
Is there such a thing?

<Image Name="MapImage" Stretch="None">
    <Image.Source>
        <DrawingImage>
            <DrawingImage.Drawing>
                <DrawingGroup>
                    <DrawingGroup.Children>
                        <ImageDrawing ImageSource="{Binding ForestArea}" Rect="{Binding Rect}"/>

<!-- Repeat the campsite as needed -->
                        <ImageDrawing ImageSource="{StaticResource CampSite}" Rect="{Binding Campsite[0].Rect}" />
                        <ImageDrawing ImageSource="{StaticResource CampSite}" Rect="{Binding Campsite[1].Rect}" />
                        <ImageDrawing ImageSource="{StaticResource CampSite}" Rect="{Binding Campsite[2].Rect}" />
                    </DrawingGroup.Children>
                </DrawingGroup>
            </DrawingImage.Drawing>
        </DrawingImage>
    </Image.Source>
</Image>
+4
source share
1 answer

, ItemsControl ItemTemplate Canvas DrawingGroup. Canvas - , :

<!-- Campsites needs to contain an observable collection of all your campsites -->
<ItemsControl ItemsSource="{Binding Campsites}">
    <!-- Set a canvas as the panel in whcih the items are rendered -->
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas>
                <Canvas.Background>
                    <!-- Set the forest area as background image of the canvas -->
                    <ImageBrush ImageSource="{Binding ForestArea}" />
                </Canvas.Background>
            </Canvas>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <!-- Display campsite image with the respective x, y, width, height -->
            <Image Source="{StaticResource CampSite}" 
                    Canvas.Left="{Binding Rect.X}"
                    Canvas.Top="{Binding Rect.Y}"
                    Width="{Binding Rect.Width}"
                    Height="{Binding Rect.Height}"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>
+2

Source: https://habr.com/ru/post/1525937/


All Articles