Using Binding to position a Collection of elements - Take 2

Back in October 2007 (wow, that long ago!) I blogged about how to use binding to position a collection of elements within an ItemsControl.
I talked about how Canvas.Top and Canvas.Left wouldn’t work when applied directly to the element because of that isn’t the child of the ItemPanel - a contentpresenter gets in the way.
I love it when you work with a technology for a long time, think you know most there is to know and come across something so stupidly obvious you’re stunned and delighted. This happened the other day.
I was aware of ItemsControl’s ItemContainerStyle property that would be applied to the resulting ContentPresenters, but I’d never considered using Binding in that style. Guess what? It just totally works. Of course it does. D’oh.
Here’s a much better solution to the one proposed in that previous post:
xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation“
xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml“
xmlns:draw=”clr-namespace:System.Drawing;assembly=System.Drawing”>

  1. <Page.Resources><br /> <x:Array x:Key="myArray" Type="{x:Type draw:Point}"><br /> <draw:Point X="10" Y="20"/><br /> <draw:Point X="20" Y="10"/><br /> <draw:Point X="30" Y="50"/><br /> </x:Array><br /> </Page.Resources>
  2. <ItemsControl ItemsSource="{Binding Source={StaticResource myArray}, Path=.}"><br /> <ItemsControl.ItemContainerStyle><br /> <Style><br /> <Setter Property="Canvas.Top" Value="{Binding Y}" /><br /> <Setter Property="Canvas.Left" Value="{Binding X}" /><br /> </Style><br /> </ItemsControl.ItemContainerStyle><br /> <ItemsControl.ItemTemplate><br /> <DataTemplate><br /> <Rectangle Fill="Red" Width="10" Height="10" /><br /> </DataTemplate><br /> </ItemsControl.ItemTemplate><br /> <ItemsControl.ItemsPanel><br /> <ItemsPanelTemplate><br /> <Canvas IsItemsHost="True" /><br /> </ItemsPanelTemplate><br /> </ItemsControl.ItemsPanel><br /> </ItemsControl>


The example above is Kaxaml-ready for your delectation.
Tags: WPF