MVVM ObservableCollection<> ListView
目标:在ListView中,设两列,一列表示人的姓名,一列表示年龄,用ObservableCollection<>来实现。
编程:
1)定义类Person
public class ABC:INotifyPropertyChanged
{
#region INotifyPropertyChanged 成员
public event PropertyChangedEventHandler PropertyChanged;
public void RaisePropertyChanged(string PropertyName)
{
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
}
#endregion
private string name;
public string Name
{
get { return name; }
set
{
if (name!=value)
{
name = value;
RaisePropertyChanged("IP");
}
}
}
private int age;
public int Age
{
get { return age; }
set
{
if (age != value)
{
age = value;
RaisePropertyChanged("Age");
}
}
}
public ABC() { }
public ABC(string ip,int age) { this.Name = ip; this.Age = age; }
2).按照MVVM的模式,设计一个ViewModel,在此类中定义ObservableCollection<>:
public Class PracticeViewModel
{
public ObservableCollection<ABC> collection = new ObservableCollection<ABC>();
public void InitialCollection()
{
collection.Add(new ABC("Betty", 23));
collection.Add(new ABC("Jully", 24));
collection.Add(new ABC("Tom", 25));
}
public PracticeViewModel()
{
InitialCollection();
}
}
3).定义数据上下文
PracticeViewModel vm = new PracticeViewModel();
this.DataContext = vm.collection;
4).写xaml代码
<ListView ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn Header="姓名" DisplayMemberBinding="{Binding Name}"/>
<GridViewColumn Header="年龄" DisplayMemberBinding="{Binding Age}"/>
</GridView>
</ListView.View>
</ListView>
现在的问题是:还没搞清楚listView的ItemSource里面应该Binding 什么,虽然老师讲了,当时感觉明白了,结果试了试发现还是有问题,继续学习。