Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canvas as ListBox ItemTemplate

My environment is windows phone 7.1.

I have the following code:

     <ListBox  ItemsSource="{Binding Path=Items}">
        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <Canvas Background="Black" />
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <Canvas  Width="200" Height="400"
                    Canvas.Top="400"> <====== This is not working
                   ... Some content ...
                </Canvas>
            </DataTemplate>
        </ListBox.ItemTemplate>

There is a ListBox that has a Canvas as ItemsPanel.

The ListBoxItems itself are also of type Canvas. For the ListBoxItems I set Canvas.Top =400, i expect the items to show with an offset of 400 in the ItemsPanel.

Unfortunately this doesn't work, the items are rendered at an offset of 0 as shown in this image (the ItemsPanel is black, the colorful rectangle is a listitem):

enter image description here

Why arent the ListBoxItems rendered at an offset of 400?

like image 563
thumbmunkeys Avatar asked Jan 23 '26 01:01

thumbmunkeys


2 Answers

You are setting the Canvas.Top on the contents of the ListBoxItems not the actual items

When using a canvas as item panel you have to remember that your datatemplated objects are wrapped in ListboxItems

ListBox
  Canvas <- your itemtemplate
    ListBoxItem
      Canvas <- your datatemplate

solution:

<ListBox.ItemContainerStyle>
  <Style TargetType="ListBoxItem">
     <Setter Property="Canvas.Top" Value="400"/>
  </Style>
</ListBox.ItemContainerStyle>
like image 106
Jesper Larsen-Ledet Avatar answered Jan 24 '26 14:01

Jesper Larsen-Ledet


Try adding this to your ListBox

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
        <Setter Property="HorizontalContentAlignment" Value="Stretch" />
    </Style>
</ListBox.ItemContainerStyle>

Because you see, the Black Area is the ListBox, but not your ListBoxItem. Due a "commonly known bug", if we still can call it that, the ListBoxItem doesn't stretch, unless you add the code above.

like image 40
Claus Jørgensen Avatar answered Jan 24 '26 13:01

Claus Jørgensen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!