Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can blocks of XAML be repeated, foreach-style?

Tags:

c#

wpf

xaml

I am making a WPF application that consists of a base-Map with a series of Campsites overlaid on top.

The number of campsites is updated dynamically in a collection, so I want to write XAML that will create more campsite Images as needed.

But I'm not familiar with any sort of foreach construct, or other repeating code in XAML.
Does such a thing exist?

<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>
like image 656
abelenky Avatar asked Nov 01 '22 05:11

abelenky


1 Answers

You can achieve the desired behavior pretty easy, if you use an ItemsControl with an according ItemTemplate to display the images in a Canvas instead of the DrawingGroup. Canvas is a panel control which allows positioning items by coordinates:

<!-- 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>
like image 130
Marc Avatar answered Nov 12 '22 22:11

Marc