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

C# WPF ListView控件绑定集合后新增项不显示问题排查

WPF ListView绑定无展示内容问题修复方案

核心遗漏点

  • CarCollection是私有字段,WPF绑定仅支持公共属性,无法识别私有字段作为绑定源
  • 使用List<T>作为集合容器,该类未实现INotifyCollectionChanged接口,集合元素增删时无法主动通知UI刷新
  • 未设置窗体的DataContext,绑定表达式找不到对应的数据源
  • Car类访问修饰符为internal,跨程序集场景下会导致绑定失败,不符合绑定模型类的规范要求

修正代码

Car类修改

using System;

namespace CarClasses
{
    // 改为public公共类
    public class Car
    {
        string _brand = "";
        string _model = "";

        public Car(string brand, string model)
        {
            _brand = brand;
            _model = model; 
        }

        public string Brand
        {
            get { return _brand; }  
            set { _brand = value; }
        }

        public string Model
        { 
            get { return _model; } 
            set { _model = value; }
        }  
    }
}

MainWindow.xaml.cs修改

using System;
using System.Collections.ObjectModel; // 引入动态集合命名空间
using System.Windows;
using CarClasses;

namespace GridViewListView
{
    public partial class MainWindow : Window
    {
        // 改为公共属性,集合类型替换为支持变更通知的ObservableCollection
        public ObservableCollection<Car> CarCollection { get; set; } = new ObservableCollection<Car>();
        public MainWindow()
        {
            InitializeComponent();
            // 设置数据上下文为当前窗体实例,让绑定能找到对应属性
            this.DataContext = this;
        }

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            Car newCar = new Car(txtBrand.Text, txtModel.Text);
            CarCollection.Add(newCar);  
            txtBrand.Text = "";
            txtModel.Text = "";
        }
    }
}

XAML代码无需修改,原有绑定逻辑可正常生效

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 22:54:04