WPF DataGrid问题与ObservableCollection和刷新DataGrid

时间:2019-03-18 09:18:20

标签: c# wpf

将新项目保存到数据库后,DataGrid仅显示此新项目。

例如,我的收藏夹中有

  • 0000

尝试添加:

  • 1111
  • 2222

我所期望的:

  • 0000
  • 1111
  • 2222

我得到的是

  • 1111
  • 2222

我的VieModel继承自INotifyPropertyChanged

在我的ViewModel中,我加载数据:

using (var context = new DbContext())
        {
            var listOfbranches = context
                .Branches_Table
                .ToList();

            Branches = new ObservableCollection<Branch>(listOfbranches);
        }

我已经定义了ObservableCollection(可能是错误的定义):

private ObservableCollection<Branch> _Branches { get; set; }
    public ObservableCollection<Branch> Branches
    {
        get { return _Branches; }
        set
        {
            _Branches = value;
            OnPropertyChanged("Branches");
        }
    }

然后按操作按钮:

public void MyAction()
    {
        var listOfbranches = new List<Branch>
        {
            new Branch { BranchCode  = "1111", BranchID = "12121212"},
            new Branch {BranchCode  = "2222", BranchID = "21212121"}
        };

        using (var context = new DbContext())
        {
            context.Branches_Table.AddRange(listOfbranches );
            context.SaveChanges();
            Branches = new ObservableCollection<Branch>(listOfbranches);
        }
    }

在我的视图xaml中:

<DataGrid ItemsSource="{Binding Branches,Mode=TwoWay,NotifyOnSourceUpdated=True,UpdateSourceTrigger=PropertyChanged}" Grid.Row="1">

任何评论将不胜感激!

0 个答案:

没有答案