Avalonia中ItemsControl用Grid作ItemsPanelTemplate绑定行列索引异常
Avalonia ItemsControl Grid布局元素重叠的修复方案
问题核心:Grid的Grid.Row/Grid.Column附加属性仅对Grid的直接子元素生效,但ItemsControl会为每个Item自动生成ContentPresenter作为容器,你之前直接在Button上绑定这些属性,Grid无法识别,导致所有元素默认处于(0,0)位置,最终重叠。
修复方法(标准方案)
通过ItemsControl.ItemContainerStyle为每个Item的容器(ContentPresenter)绑定Grid行列属性,让Grid能正确识别每个Item的位置:
修改后的View代码:
<ItemsControl BorderBrush="Black" BorderThickness="5" Margin="5" ItemsSource="{Binding Items}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> </Grid> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <!-- 为ContentPresenter设置Grid行列绑定 --> <ItemsControl.ItemContainerStyle> <Style TargetType="ContentPresenter"> <Setter Property="Grid.Row" Value="{Binding YIndex}"/> <Setter Property="Grid.Column" Value="{Binding XIndex}"/> </Style> </ItemsControl.ItemContainerStyle> <ItemsControl.ItemTemplate> <DataTemplate> <Button BorderBrush="Red" BorderThickness="2" Padding="0" Background="White"> <StackPanel Width="200" Height="100" Background="{Binding Color}"> <TextBlock Margin="10" FontSize="20" FontWeight="Bold" TextAlignment="Center" Text="{Binding Name}"></TextBlock> <TextBlock Margin="10" FontSize="20" FontWeight="Bold" TextAlignment="Center" Text="{Binding Price}"></TextBlock> </StackPanel> </Button> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl>
补充说明
之前用WrapPanel能正常显示,是因为WrapPanel会自动按顺序排列子元素,不需要依赖附加属性定位,所以不受容器层级影响。
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

