Reputation: 64720
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>
Upvotes: 5
Views: 3657
Reputation: 13194
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>
Upvotes: 2