我在遵循MVVM模式。我有一个listview控件,它有多个复选框。我的视图模型有一个集合,它被限制为listview控件。
public ObservableCollection<Student> students{ get; private set; }
private ObservableCollection<Student> _displays { get; set; }视图模型不知道任何关于视图的信息,因此它不能访问listview控件
我试着用下面的方法来定义学生类
public class Student: INotifyPropertyChanged
{
public string Name{ get; set; }
public string class { get; set; }
//Provide change-notification for IsSelected
private bool _fIsSelected = false;
public bool IsSelected
{
get { return _fIsSelected; }
set
{
_fIsSelected = value;
this.OnPropertyChanged("IsSelected");
}
}
}现在,当用户选择/取消选中复选框时,我希望在视图模型中执行一些操作。如何才能做到这一点?这是正确的方式来定义以上的类?
发布于 2014-04-07 08:11:55
您的Student类知道它的值何时变化,所以只需要在视图模型中的Student对象集合中添加一个PropertyChanged处理程序。通过这种方式,当Student类的值发生变化时,可以通知视图模型。试着做这样的事情:
foreach (Student student in students)
{
student.PropertyChanged += Item_PropertyChanged;
}..。
private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "IsSelected")
{
// The IsSelected property was changed
}
}请注意,您必须向集合中的每个项添加一个处理程序。您可以在循环中这样做,如上面所示,或者通过扩展ObservableCollection<T>类并重写Add、Insert和Remove方法以及构造函数。
更新>>>
在上面的最后一段中,您可以扩展ObservableCollection<T>类并重写Add和Remove方法以及构造函数.最基本的情况是,您可以这样做:
public class Students : ObservableCollection<Student>
{
public Students(IEnumerable<Student> students)
{
foreach (Student student in students) Add(student);
}
public new void Add(T item)
{
item.PropertyChanged += Item_PropertyChanged;
base.Add(item);
}
public new bool Remove(T item)
{
item.PropertyChanged -= Item_PropertyChanged;
return base.Remove(item);
}
private void Item_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
// Notify of all item property changes
NotifyPropertyChanged(e.PropertyName);
}
// Implement the INotifyPropertyChanged interface properly here
}此方法的好处是,您可以将一个处理程序附加到集合,而不必手动将它们附加到每个项:
Students.PropertyChanged += Item_PropertyChanged;https://stackoverflow.com/questions/22906583
复制相似问题