MVVM で、プロパティ NumberOfAdults と NumberOfChildren を更新して UI で更新する方法は何ですか? より一般的に言えば、People ビュー モデルはどのように更新をキャッチし、コンテンツに依存するプロパティを更新するのOberservableCollection<Person>
でしょうか?
このソリューションでは、XAML バインディング構文をより高度に使用する必要があります。それは何ですか?
Person ビュー モデル
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>