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

动态创建的TabItem中ListBox无法显示数据的解决方法

解决WPF TabItem中ListBox内容为空的问题

嘿,我一眼就揪出问题所在了——WPF的数据绑定系统不支持直接绑定字段!你在MyTabItem里定义的Products是个字段(public List<Product> Products;),但WPF只能识别带get/set的属性,这就是ListBox显示空内容的核心原因。

下面给你一步步的修复方案:

1. 把Products字段改成属性

首先修改MyTabItem类,将Products从字段转为CLR属性。如果后续需要动态更新集合内容(比如新增/删除产品时自动刷新UI),推荐用ObservableCollection<T>代替List<T>,它自带集合变化通知能力:

public class MyTabItem : TabItem
{
    // 用ObservableCollection实现集合变化自动通知UI
    public ObservableCollection<Product> Products { get; set; } = new ObservableCollection<Product>();
}

如果只是静态展示数据,用普通List属性也可以:

public class MyTabItem : TabItem
{
    public List<Product> Products { get; set; }
}

2. 调整后台赋值代码

如果用了ObservableCollection,后台赋值时要对应调整:

foreach (var group in repository.Products) { 
    var tab = new MyTabItem(); 
    tab.Header = group.Key; 
    // 将分组数据转换为ObservableCollection
    tab.Products = new ObservableCollection<Product>(group.AsEnumerable()); 
    tab.FontSize = 16; 
    TabControlProducts.Items.Add(tab); 
} 
TabControlProducts.SelectedIndex = 0;

3. 简化XAML绑定(可选但更优雅)

其实TabControl的ContentTemplate的DataContext就是当前的MyTabItem,你完全不用靠RelativeSource去查找祖先,直接绑定Products就行,代码更简洁:

<TabControl Grid.Row="1" Grid.Column="1" x:Name="TabControlProducts">
    <TabControl.ContentTemplate>
        <DataTemplate>
            <ListBox FontSize="16" ItemsSource="{Binding Products}" Visibility="Visible">
                <ListBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <TextBlock Text="{Binding Path=Code.MainGroup}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.MainForm}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.SubForm}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.Finishing}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.MaterialGroup}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.MaterialSort}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.Attest}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.Sizing}"></TextBlock>
                            <TextBlock Text="{Binding Path=Code.SubSizing}"></TextBlock>
                        </StackPanel>
                    </DataTemplate>
                </ListBox.ItemTemplate>
            </ListBox>
        </DataTemplate>
    </TabControl.ContentTemplate>
</TabControl>

额外验证点

最后再确认两个小细节:

  • repository.Products确实是有效的IGrouping集合,每个分组内有实际的Product数据;
  • Product类中的Code是公共属性,且Code内部的MainGroup、MainForm等子属性也都是公共属性(不是字段),否则XAML绑定同样会失效。

按上面的步骤改完,你的ListBox就能正常显示分组内的产品数据啦!

内容的提问来源于stack exchange,提问作者amamedov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:13:11