WPF中如何将List绑定至ListView自定义UserControl?
核心问题原因
你的ProductLineStyle UserControl在构造函数中设置了this.DataContext = this;,这会覆盖ListView ItemTemplate默认传递的DataContext(也就是每个Product对象)。此时TextBlock绑定的是UserControl自身的空属性,所以出现项数正确但内容为空的现象。
解决步骤
1. 修改UserControl后台代码
移除构造函数中的this.DataContext = this;,让UserControl继承父级(ListView的每个列表项)的DataContext:
public ProductLineStyle() { InitializeComponent(); // 移除 this.DataContext = this; } // 这些属性可直接删除(不再用到) // public string ProductID { get; set; } // public string ProductName { get; set; } // public int ProductPrice { get; set; } // public int ProductQTé { get; set; }
2. 清理ListView的冗余代码
移除ListView中多余的<ItemsControl></ItemsControl>节点,ListView本身就是ItemsControl的子类,嵌套会干扰正常渲染:
<ListView x:Name="ProductTable" Background="Transparent" ItemsSource="{Binding GetProducts}"> <ListView.ItemTemplate> <DataTemplate> <v:ProductLineStyle/> </DataTemplate> </ListView.ItemTemplate> </ListView>
3. 确认数据绑定逻辑
确保后台的GetProducts()方法返回List<Product>类型,赋值逻辑正确:
// 示例:从数据库获取并返回Product集合 private List<Product> GetProducts() { // 替换为实际数据库查询逻辑 return new List<Product> { new Product("P001", "测试产品", 100, 5), new Product("P002", "另一产品", 200, 3) }; } // 后台直接赋值(若不用XAML绑定) ProductTable.ItemsSource = GetProducts();
注:如果用XAML的
ItemsSource="{Binding GetProducts}",需确保ListView的DataContext指向包含GetProducts属性的类,否则直接用后台代码赋值更直观。
原理说明
当ListView的ItemsSource绑定到List<Product>后,每个列表项的DataContext会自动设置为对应的Product对象。移除UserControl的DataContext强制设置后,内部TextBlock的{Binding ProductID}会自动查找父级DataContext(即Product对象)的对应属性,从而正确显示内容。
内容的提问来源于stack exchange,提问作者amene127

