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

MVVM模式下DataGrid与ViewModel数据绑定问题咨询

你一共遗漏了4处核心配置:

    1. 绑定源属性访问级别错误:WPF绑定仅支持公共属性,你当前UserItems是默认私有访问级别的字段,无法被绑定系统识别。
      修改后的ViewModel属性代码:
    // 改成公共属性,标准写法加属性变更通知
    private ObservableCollection<User> _userItems = new ObservableCollection<User>();
    public ObservableCollection<User> UserItems
    {
        get => _userItems;
        set
        {
            _userItems = value;
            OnPropertyChanged(nameof(UserItems));
        }
    }
    
    1. INotifyPropertyChanged接口未完整实现:你只声明了事件,没有实现通知触发方法,后续属性变更无法通知UI更新。
      补充ViewModel的通知方法:
    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }
    
    1. 模拟数据加载方法未触发:fetchgrid是私有方法,没有任何调用入口,集合里始终没有数据。可以放在ViewModel的构造函数中调用:
    public UserViewModel()
    {
        fetchgrid();
    }
    
    1. View未设置DataContext绑定源:没有给UserView指定绑定的上下文对象,XAML的{Binding UserItems}找不到对应的数据源。两种实现方式二选一:
      方式1:在UserView.xaml.cs后台构造函数中设置:
    public UserView()
    {
        InitializeComponent();
        this.DataContext = new UserViewModel();
    }
    
    方式2:直接在UserView.xaml的根节点添加DataContext声明:
    <Window x:Class="你的命名空间.UserView"
            xmlns:vm="clr-namespace:你的ViewModel所在命名空间">
        <Window.DataContext>
            <vm:UserViewModel/>
        </Window.DataContext>
        <!-- 你的原有Grid代码 -->
    </Window>
    

可选优化项(按需修改)

如果后续需要修改User实例的firstname/lastname属性后UI同步更新,需要让User类也实现INotifyPropertyChanged接口。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 09:39:03