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

WPF中CollectionViewSource无法更新UI问题求助

解决WPF ListView点击按钮不填充数据的问题

你的问题核心在于MainWindowViewModel没有实现INotifyPropertyChanged接口,WPF的数据绑定依赖这个接口监听属性值变化。当你在按钮点击事件里给DoorCollection赋值时,UI无法感知到这个变化,所以ListView不会更新显示。

修复步骤:

  1. 让MainWindowViewModel实现INotifyPropertyChanged接口,和Door类的实现方式一致。
  2. 修改DoorCollection的setter方法,赋值后触发PropertyChanged事件。
  3. 确保窗口构造函数中已正确设置DataContext(比如DataContext = new MainWindowViewModel();)。

修改后的MainWindowViewModel代码:

public class MainWindowViewModel : INotifyPropertyChanged
{
    private ICollectionView _doorView;
    public ICollectionView DoorCollection
    {
        get { return _doorView; }
        set
        {
            _doorView = value;
            OnPropertyChanged(nameof(DoorCollection));
        }
    }

    public ICommand GetAllDoorItemsCommand { get; set; }

    public MainWindowViewModel()
    {
        GetAllDoorItemsCommand = new RelayCommand<object>(GetAllItems);
    }

    private void GetAllItems(object obj)
    {
        var items = new List<Door>();
        items.Add(new Door() { Name = "Front", Open = true });
        items.Add(new Door() { Name = "Back", Open = false });
        DoorCollection = CollectionViewSource.GetDefaultView(items);
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
}

额外说明:

  • 无需调用DoorCollection.Refresh(),触发PropertyChanged事件后UI会自动更新绑定。
  • 确保你的RelayCommand实现正确(标准RelayCommand需实现ICommand接口,处理CanExecute和Execute逻辑)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 16:40:18