3
votes

I want to add a dynamic number of ellipses to a canvas and set the ellipse position (canvas.top, canvas.left). I tried binding to an ItemsControl but it each item (ellipse) has a container, so I cant set the ellipses position directly. I don't want an items container, I just want a canvas that contains ellipses.

Can this be done?

2

2 Answers

2
votes

Try this - worked for me -- I use it to freely place textblocks on a canvas.

Re: Re: Positioning Items when Canvas is the ItemsPanel of an ItemsControl 02-26-2010 7:17 AM |

There is an alternative simpler solution that does work in silverlight 3.

 
 <Canvas>
  <ItemsControl ItemsSource={Binding MyItems}>
    <ItemsControl.ItemTemplate>
      <DataTemplate>
        <Canvas>
          <TextBlock Canvas.Left={Binding Left} Canvas.Top={Binding Top} Text={Binding Text} />
        </Canvas>
      </DataTemplate>
    </ItemsControl.ItemTemplate>
  </ItemsControl>
</Canvas>

If the MyItems is a list of items that are of a class that has Left, Top and Text public properties, this works fine. I have also tested with Line and Border to draw simple bar graph graphics in silverlight 3.

From the bottom of this post: http://forums.silverlight.net/forums/p/29753/450510.aspx#450510

Combine it with a Silverlight DataTemplateSelector and you can change the objects you draw based on view model properties:

http://www.codeproject.com/KB/silverlight/SLTemplateSelector.aspx

2
votes

Ordinarily I would say use an ItemsControl in conjunction with a Canvas:

<ItemsControl ItemsSource="{Binding Ellipses}">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <Canvas/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemsContainerStyle>
        <Style>
            <Setter Property="Canvas.Left" Value="{Binding Left}"/>
            <Setter Property="Canvas.Top" Value="{Binding Top}"/>
        </Style>
    </ItemsControl.ItemsContainerStyle>
</ItemsControl>

But in a display of Silverlight suckiness, the ItemContainerStyle property does not work on ItemsControl. It has support in ItemsControl, but it's not exposed by ItemsControl itself. Instead, it's up to subclasses of ItemsControl - such as ListBox - to expose it. Oh, and those subclasses have to be provided by Microsoft because the functionality is protected internal, so you can't just subclass ItemsControl and expose this stuff yourself. :S

So you could use ListBox instead, possibly by subclassing it and changing its item container to something simpler than a ListBoxItem. Or you could just use ListBox directly and fiddle around until the ListBoxItems look the way you want them to (i.e. not selected).