如何使用observable集合刷新网格

时间:2014-07-11 10:09:53

标签: wpf mvvm datagrid observablecollection

我是mvvm的初学者在开发时我遇到了问题,即我正在尝试用可观察的集合刷新我的网格,但是在我的情况下我没有使用下面的代码,请让我知道我在哪里做错了< / p>

窗口的datacontext属性

 public ProjectTabView()
        {
            InitializeComponent();
            var vm = new ProjectTabViewModel();
            this.DataContext = vm;
            vm.ClosingRequest += (sender, e) => this.Close();

        }

XAML

<DataGrid ItemsSource="{Binding BindFiles,UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single"></DataGrid >

视图模型中的属性

 public class ProjectTabViewModel : ViewModelBase, INotifyPropertyChanged
    {

    ObservableCollection<Project> _BindFiles;
        public ObservableCollection<Project> BindFiles
        {
            get
            {
                return _BindFiles;
            }
            set
            {
                _BindFiles = value;
                RaisePropertyChanged(() => BindFiles);
            }
        }
}

**constructor**

     BindFiles = new ObservableCollection<Project>();

**ViewModel**

public void Bindfiletab()
        {
            List<Project> obj = ProjectTabModel.FilesBinding(GlobalProjectID);
            ObservableCollection<Project> obsrvbl = new ObservableCollection<Project>(obj);
            if (obsrvbl.Count > 0)
            {
                BindFiles.Clear();
                foreach (var item in obsrvbl)
                {
                    BindFiles.Add(item);
                }
            }

        }



public void Execute(object sender)
     {
        GalaSoft.MvvmLight.Threading.DispatcherHelper.CheckBeginInvokeOnUI(()=>
         {
          //here i have called my above bind file tab method to refresh  my grid
          } 
     }

1 个答案:

答案 0 :(得分:0)

您的问题似乎发生在这里:

public void Bindfiletab()
{
    List<Project> obj = ProjectTabModel.FilesBinding(GlobalProjectID);
    ObservableCollection<Project> obsrvbl = new ObservableCollection<Project>(obj);
    if (obsrvbl.Count > 0)
    {
        BindFiles.Clear();
        foreach (var item in obsrvbl)
        {
            BindFiles.Add(item);
        }
    }
}

我只能假设这会填充obj集合:

List<Project> obj = ProjectTabModel.FilesBinding(GlobalProjectID);

然后填充obsrvbl集合:

ObservableCollection<Project> obsrvbl = new ObservableCollection<Project>(obj);

很多代码都是不必要的......请尝试这样做:

public void Bindfiletab()
{
    List<Project> obj = ProjectTabModel.FilesBinding(GlobalProjectID);
    BindFiles = new ObservableCollection<Project>(obj);
}