0
在MVVM中,有什麼打算技術刷新屬性NumberOfAdults和NumberOfChildren要在UI上更新?更一般地說,People view模型如何捕獲更新並刷新依賴於OberservableCollection<Person>
上的內容的屬性?當T更新ObservableCollection <T>,刷新其他依賴屬性的建議
該解決方案需要更高級地使用XAML綁定語法。它是什麼?
該人士看來模式
public class Person : INotifyPropertyChanged
{
private int _age;
public int Age
{
get { return _age; }
set { _age = value; NotifyPropertyChanged("Age"); }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; NotifyPropertyChanged("Name"); }
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
人民視圖模型
using System;
using System.ComponentModel;
using System.Collections.ObjectModel;
public class PeopleViewModel : INotifyPropertyChanged
{
public PeopleViewModel()
{
People.Add(new Person { Name = "Happy", Age = 12 });
People.Add(new Person { Name = "Sleepy", Age = 15 });
People.Add(new Person { Name = "Sneezy", Age = 17 });
People.Add(new Person { Name = "Grumpy", Age = 45 });
People.Add(new Person { Name = "Dopey", Age = 50 });
People.Add(new Person { Name = "Bashful", Age = 60 });
People.Add(new Person { Name = "Doc", Age = 75 });
}
private ObservableCollection<Person> _people = new ObservableCollection<Person>();
public ObservableCollection<Person> People
{
get { return _people;}
set { _people = value;}
}
public int NumberOfAdults
{
get
{
int count = 0;
foreach (Person p in People)
{
if (p.Age >= 18)
{
count += 1;
}
}
return count;
}
}
public int NumberOfChildren
{
get
{
int count = 0;
foreach (Person p in People)
{
if (p.Age < 18)
{
count += 1;
}
}
return count;
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
主XAML
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel>
<Label Content="{Binding Path=NumberOfAdults}"></Label>
<Label Content="{Binding Path=NumberOfChildren}"></Label>
<DataGrid ItemsSource="{Binding Path=People}"></DataGrid>
</StackPanel>
</Window>
在您的ViewModel類中爲'Person'掛鉤propertyChanged,並從那裏爲其依賴屬性引發propertyChanged。 –
也許我誤解了你的評論,但似乎這會增加視圖模型之間的耦合。 – bartonm
'Person'是我設想的模型類,而不是ViewModel類。引用ViewModel類中的Model類完全沒問題。 –