WP7 ListBox ItemPanel SelectChanged选择lastItem

时间:2011-06-17 04:35:55

标签: windows-phone-7 listbox

我有一个列表框,它使用ItemsPanel中的画布来使用边距上的绑定来布局项目,这一切都很有效。但是,单击列表框只会触发一次,并始终返回列表框中的最后一项。

守则:

<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>

为什么我只得到列表中的最后一项?

1 个答案:

答案 0 :(得分:1)

如果你使用Canvas进行布局,它会将ItemContainerStyle中的项目放在另一个上面,因此放在画布中的最后一项将是唯一可见的项目。想象一下,将一组玻璃窗放在一起,你的物品只需在每个新玻璃上下拉。即使在底部绘制项目,您仍然只能触摸顶部玻璃。

解决方案:

尝试移动

Margin =“{Binding XYMargin}”

退出数据模板并放入ItemContainerStyle。

示例:(为简洁起见而简化):

<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>
相关问题