我将View的数据上下文设置为ViewModel,如下所示
PersonVM pvm = null;
public MainPage()
{
this.InitializeComponent();
pvm = new PersonVM();
this.DataContext = pvm;
}
然后点击按钮我想在我的收藏中添加更多项目
private void Btn_PointerPressed(object sender, Windows.UI.Xaml.Input.TappedRoutedEventArgs e)
{
pvm.DataSource.Add(new PersonVMWrapper(new PersonModel() { Name = "asdasd", Age = 23 }));
}
这是我的ViewModel,我显然做错了什么,但无法搞清楚..
namespace App3vv.ViewModel
{
public class PersonVMWrapper : INotifyPropertyChanged
{
PersonModel _pm = null;
public PersonVMWrapper(PersonModel pm)
{
_pm = pm;
}
public string Name
{
get
{
return "mr." + _pm.Name;
}
set { RaisePropertyChanged("Name"); }
}
public string Age
{
get
{
return _pm.Age.ToString() + " years";
}
set { RaisePropertyChanged("Age"); }
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
public class PersonVM : INotifyPropertyChanged
{
private ObservableCollection<PersonVMWrapper> personDataSource;
public PersonVM()
{
this.DataSource.Add(new PersonVMWrapper(new PersonModel() { Name = "John", Age = 32 }));
this.DataSource.Add(new PersonVMWrapper(new PersonModel() { Name = "Kate", Age = 27 }));
this.DataSource.Add(new PersonVMWrapper(new PersonModel() { Name = "Sam", Age = 30 }));
DataSource.CollectionChanged += DataSource_CollectionChanged;
}
void DataSource_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
this.RaisePropertyChanged("DataSource");
}
public ObservableCollection<PersonVMWrapper> DataSource
{
get
{
if (this.personDataSource == null)
{
this.personDataSource = new ObservableCollection<PersonVMWrapper>();
}
return this.personDataSource;
}
set
{
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = this.PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
编辑:我实现了CollectionChange,但我的View仍然没有添加新项目..