ItemsControl designed to create dynamic collections of user interface controls from other collections, even for data collections other than the UI.
You can create an ItemsControl template for drawing on Canvas . The ideal way is to set the support panel on Canvas and then set the Canvas.Left and Canvas.Top for immediate children. I could not get this to work because the ItemsControl wrapping its children with containers, and it is difficult to set the Canvas properties in these containers.
Instead, I use Grid as bin for all objects and draw them each on my Canvas . With this approach, there is some overhead.
<ItemsControl x:Name="Collection" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate DataType="{x:Type local:MyPoint}"> <Canvas HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <Ellipse Width="10" Height="10" Fill="Black" Canvas.Left="{Binding X}" Canvas.Top="{Binding Y}"/> </Canvas> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
Here is the code I used to create the source collection:
List<MyPoint> points = new List<MyPoint>(); points.Add(new MyPoint(2, 100)); points.Add(new MyPoint(50, 20)); points.Add(new MyPoint(200, 200)); points.Add(new MyPoint(300, 370)); Collection.ItemsSource = points;
MyPoint is a custom class that behaves like a version of System . I created it to demonstrate that you can use your own custom classes.
One detail: you can bind the ItemsSource property to any collection you want. For example:
<ItemsControls ItemsSource="{Binding Document.Items}">
For more information about ItemsControl and how it works, check out these documents: MSDN Library Reference ; Data Templates Dr WPF series on ItemsControl .
Josh G May 20 '09 at 20:35 2009-05-20 20:35
source share