我有这段代码
这是我的PersonModel PersonModel.cs
public class PersonModel
{
List<Person> list = new List<Person>();
#region Constructors
public PersonModel()
{
}
#endregion Constructors)
#region Methods
public List<Person> GetPersons()
{
list.Add(new Person("Иванов", "Иван", "Иванович", new DateTime(1980, 5, 10), Gender.Male));
list.Add(new Person("Петр", "Петрович", "Петров", new DateTime(1977, 9, 21), Gender.Male));
list.Add(new Person("Виктория", "Викторовна", "Викторова", new DateTime(1991, 1, 7), Gender.Female));
return list;
}
public List<Person> SetPersons()
{
list.Add(new Person("Маташков", "Сергей", "Сергеевич", new DateTime(1980, 5, 10), Gender.Male));
return list;
}
#endregion Methods
}
这是我的PersonViewModel PersonsViewModel.cs
public class PersonsViewModel<TViewType> : INotifyPropertyChanged, IViewModel where TViewType : IView, new()
{
private readonly IView _view;
private readonly PersonModel _model;
public ObservableCollection<Person> Persons { get; set; }
public RelayCommand OkCommand { get; private set; }
private string _str;
public PersonsViewModel()
{
this._view = new TViewType();
this._model = new PersonModel();
this.Persons = new ObservableCollection<Person>(this._model.GetPersons());
this.OkCommand = new RelayCommand(o => this.OKRun());
_str = "Кнопка";
this._view.SetDataContext(this);
this._view.ShowView();
}
public string Str
{
get { return _str; }
set
{
if (_str == value)
return;
_str = value;
OnPropertyChanged("Str");
}
}
public ObservableCollection<Person> Observ
{
get { return Persons; }
set
{
if (Persons == value)
return;
Persons = value;
OnPropertyChanged("Observ");
}
}
public event PropertyChangedEventHandler PropertyChanged;
//[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
private void OKRun()
{
Str = "Refresh";
this.Persons = new ObservableCollection<Person>(this._model.SetPersons());
}
}
这是我的PersonsView
PersonsView.xaml
<DataGrid ItemsSource="{Binding Observ, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" />
我想更新Datadrid?
为什么不更新Datagrid和observablecollection?
答案 0 :(得分:0)
在你的构造函数中,你应该写:
this.Observ= new ObservableCollection<Person>(this._model.SetPersons());
而不是
this.Persons = new ObservableCollection(this._model.SetPersons());