开发者

WP7 ListBox ItemPanel SelectChanged selects lastItem

开发者 https://www.devze.com 2023-03-13 19:18 出处:网络
I have a list box that uses a canvas in the ItemsPanel to lay out the items using binding on the Margin, this all works great. However clicking on the list box only fires once and always returns the l

I have a list box that uses a canvas in the ItemsPanel to lay out the items using binding on the Margin, this all works great. However clicking on the list box only fires once and always returns the last item in the listbox.

The Code:

<Grid>
  <ListBox Name="lstItems" ItemsSource="{Binding Itemss}"  Width="Auto" Height="497"  Margin="0,40,0,10" SelectionChanged="ListBox_SelectionChanged">
    <ListBox.ItemsPanel>
      <ItemsPanelTemplate>
        <Canvas Name="cnvItems">
        </Canvas>

      </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
      <DataTemplate>
        <Grid Margin="{Binding XYMargin}">
          <Border BorderBrush="Silver" BorderThickness="5" Height="{Binding XYWidth}" Width="{Binding XYWidth}" HorizontalAlignment="Left" Margin="0,0,0开发者_开发知识库,0" Name="border5" VerticalAlignment="Top" Background="#81FFFFFF" CornerRadius="10" />
            <StackPanel Margin="5,5,0,0" HorizontalAlignment="Center" Orientation="Horizontal">
              <TextBlock Margin="0,0,0,0" Width="{Binding XYWidth}" Text="{Binding Label1}"   TextAlignment="Left"  FontSize="30" />
            </StackPanel>
        </Grid>
      </DataTemplate>
    </ListBox.ItemTemplate>
  </ListBox>

</Grid>

Any ideas why I only get the last item in the list?


If you're using the Canvas to do layout, it is laying out the items in an ItemContainerStyle one on top of another, so the last item to be put in the canvas will be the only one visible. Think of laying a set of glass panes on top of one another and your items are simply drawing lower and lower on each new glass. You can still only touch the top glass, even though the item is drawn at the bottom.

Solution:

Try moving the

Margin="{Binding XYMargin}"

out of your data template and putting into your ItemContainerStyle.

Example: (simplified for clarity):

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem">
       <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="ListBoxItem">
                <Border x:Name="LayoutRoot" 
                    Margin="{Binding XYMargin}">                                            
                    <ContentControl 
                        x:Name="ContentContainer" 
                        ContentTemplate="{TemplateBinding ContentTemplate}" 
                        Content="{TemplateBinding Content}" 

                </Border>
            </ControlTemplate>
        </Setter.Value>
       </Setter>
    </Style>
</ListBox.ItemContainerStyle>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号