1

i have to write some circles to a canvas in wpf. i have this tutorial as a base but it won't work somehow: http://www.wpf-tutorial.com/list-controls/itemscontrol/

my xaml

<ItemsControl Name="icCircles">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Background="Transparent" Width="300" Height="500"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Ellipse Canvas.Top="{Binding X}" Canvas.Left="{Binding Y}" Fill="Black" Height="5" Width="5" Stroke="Black" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

the code behind:

List<Circle> circles = new List<Circle>();

circles.Add(new Circle() { X = 50, Y = 50 });
circles.Add(new Circle() { X = 100, Y = 50 });

icCircles.ItemsSource = circles;

the circle class:

public class Circle
{
    public int X { get; set; }
    public int Y { get; set; }
}

if i add nothing to the list, i don't get anything. if i add one circle, i see it, but at X0/Y0. if i add a second one, i still see only one circle. possibly because they are at the same location.

what am i doing wrong?

el-nino
  • 399
  • 9
  • 26
  • 2
    Take a look at [this answer](http://stackoverflow.com/a/22325266/1136211). The key point is to bind Canvas.Left and Canvas.Top in an ItemContainerStyle. – Clemens Oct 23 '15 at 09:35

1 Answers1

1

You have to bind the Canvas.Left and Canvas.Top properties in a Style for the ContentPresenter that serves as item container. The Style is applied by the ItemContainerStyle property:

<ItemsControl Name="icCircles">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas Background="Transparent"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemContainerStyle>
        <Style TargetType="ContentPresenter">
            <Setter Property="Canvas.Left" Value="{Binding X}"/>
            <Setter Property="Canvas.Top" Value="{Binding Y}"/>
        </Style>
    </ItemsControl.ItemContainerStyle>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Path Fill="Black">
                <Path.Data>
                    <EllipseGeometry RadiusX="2.5" RadiusY="2.5"/>
                </Path.Data>
            </Path>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Note however that those small Ellipses are aligned at their top left corner, so it's not their center pointer at which they are drawn. You may therefore replace them by Paths with EllipseGeometries:

<ItemsControl.ItemTemplate>
    <DataTemplate>
        <Path Fill="Black">
            <Path.Data>
                <EllipseGeometry RadiusX="2.5" RadiusY="2.5"/>
            </Path.Data>
        </Path>
    </DataTemplate>
</ItemsControl.ItemTemplate>
Clemens
  • 123,504
  • 12
  • 155
  • 268