You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF中ItemsControl显示异常:所有记录重叠在一起

解决ItemsControl中记录重叠的问题

我一眼就看出问题出在你的ItemsPanel设置上啦!你现在用的是一个只定义了1行1列的Grid作为ItemsPanel,这就意味着所有的Item容器都会被塞进同一个单元格里,可不就重叠了嘛😅

问题根源分析

你在ItemContainerStyle里绑定了Grid.Row和Grid.Column到MyRow和MyColumn,但你的Grid根本没有对应数量的行和列定义——只有1行1列,就算MyRow有值,Grid也没有足够的行来放置这些Item,最终还是挤在同一个位置。

方案1:改用StackPanel实现垂直/水平排列(最简单)

如果你的需求只是让Item垂直排列,直接把ItemsPanelTemplate换成StackPanel就行,这样ItemsControl会自动帮你把每个Item依次排列,不会重叠:

<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical"/>
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

方案2:如果确实需要用Grid布局

如果你一定要用Grid来控制每个Item的行列位置,那需要做两件事:

  • 确保你的数据对象(每个Product)的MyRow和MyColumn属性都有唯一且合理的值(比如第一个Item是Row=0,第二个Row=1,以此类推);
  • 动态为Grid添加足够的行/列定义,或者提前定义好足够的行/列。

这里给你一个动态生成行的示例思路:
首先修改XAML里的ItemsPanel:

<ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>
        </Grid>
    </ItemsPanelTemplate>
</ItemsControl.ItemsPanel>

然后在后台代码里,监听ProductsCollection的变化,动态添加行定义(前提是ProductsCollection是ObservableCollection):

private void ProductsCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
    if (productsList.ItemsPanelRoot is Grid grid)
    {
        grid.RowDefinitions.Clear();
        foreach (var _ in ProductsCollection)
        {
            grid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
        }
    }
}

这样每个Item就能对应到Grid的不同行,不会再重叠了。

附上你提供的输出截图(显示重叠效果):
输出截图

内容的提问来源于stack exchange,提问作者Ashish-BeJovial

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:36:44