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

WPF中ViewModel的User_List变更后ListView未更新问题求助(EntityFramework6.0)

问题根因

你的问题本质是ViewModel实例不匹配,同时存在几处代码错误:

  • 项目中存在3个完全独立的UsersController实例,点击按钮时更新的不是和界面绑定的实例:
    1. XAML中<Window.DataContext><vw:UsersController/></Window.DataContext>会自动创建第一个实例
    2. MainWindow构造函数里controller1 = new ViewModels.UsersController();创建了第二个实例覆盖了DataContext
    3. 按钮点击事件中又新建了第三个UsersController实例,调用Increase()更新的是这个和界面完全无关的实例,自然不会触发界面刷新
  • 实体类命名错误:定义的实体类叫Userss,但其他地方引用的泛型类型是Users,类型不匹配会导致数据加载失败
  • 冗余代码破坏绑定:MainWindow中自己实现的User_List属性在set方法中直接给lst1.ItemsSource赋值,会覆盖XAML中写的绑定逻辑,且这部分代码本身完全多余

修复方案

1. 删掉XAML中重复的DataContext声明

删除XAML里的这段代码,避免重复创建ViewModel实例:

<!-- 移除该段配置 -->
<Window.DataContext>
    <vw:UsersController/>
</Window.DataContext>

2. 修改按钮点击事件,复用已有的ViewModel实例

不要在点击事件里新建UsersController,直接调用构造函数中初始化好的controller1:

private void Fetch_Data_Button_Click(object sender, RoutedEventArgs e)
{
    controller1.Increase();
    // 不需要手动调用UpdateLayout,ViewModel的PropertyChanged通知会自动触发界面更新
}

3. 修正实体类命名错误

把Users.cs里的类名从Userss改为Users,和全局引用的类型保持一致:

// 修改类名
public class Users : INotifyPropertyChanged
{
    // 类内部其余代码保持不变
}

4. 清理MainWindow的冗余代码

删除MainWindow中没用的INotifyPropertyChanged实现、user_List字段和User_List属性,简化后代码如下:

public partial class MainWindow : Window
{
    ViewModels.UsersController controller1;
    public MainWindow()
    {
        InitializeComponent();
        controller1 = new ViewModels.UsersController();
        this.DataContext = controller1;
    }
    private void Fetch_Data_Button_Click(object sender, RoutedEventArgs e)
    {
        controller1.Increase();
    }
}

5. 可选性能优化

你现在的Increase方法每次都会新建ObservableCollection实例,可以调整为清空原有集合再添加数据,避免频繁触发绑定重建:

public void Increase()
{
    Database1Entities entities = new Database1Entities();
    var data = entities.Users.ToList();
    if(User_List == null)
    {
        User_List = new ObservableCollection<Users>(data);
        return;
    }
    User_List.Clear();
    foreach(var user in data)
    {
        User_List.Add(user);
    }
}

内容的提问来源于stack exchange,提问作者Onur İn

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 13:39:00