我正在制作一个
WPF应用程序,它包含一个覆盖在顶部的基本地图和一系列露营地.
露营地的数量在集合中动态更新,因此我想编写XAML,根据需要创建更多露营地图像.
但我不熟悉任何类型的foreach构造或XAML中的其他重复代码.
这样的事情存在吗?
<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>
最佳答案 如果使用带有相应ItemTemplate的ItemsControl来在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>