, , :
- ObservableObject.cs
public abstract class ObservableObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
var handler = this.PropertyChanged;
if (handler != null)
handler(this, e);
}
protected void SetValue<T>(ref T field, T value, string propertyName)
{
if (!EqualityComparer<T>.Default.Equals(field, value))
{
field = value;
this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
}
}
MainWindow - MainWindowModel.cs
public class MainWindowModel : ObservableObject
{
private readonly ObservableCollection<Person> personCollection = new ObservableCollection<Person>()
{
new Person() { Name = "Bob", Age = 20 }
};
public ObservableCollection<Person> PersonCollection
{
get { return this.personCollection; }
}
}
MainWindow.xaml.cs .
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
MainWindow.xaml DataContext MainWindowModel.
<Window x:Class="MyApplication.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:self="clr-namespace:MyApplication">
<Window.DataContext>
<self:MainWindowModel/>
</Window.DataContext>
<ListView ItemsSource="{Binding PersonCollection}">
<ListView.ItemTemplate>
<DataTemplate>
<StackPanel>
<self:MyUserControl/>
</StackPanel>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</Window>
MyUserControl.xaml.cs ( ).
public partial class MyUserControl : UserControl
{
public MyUserControl()
{
InitializeComponent();
}
}
MyUserControl.xaml
<UserControl x:Class="MyApplication.MyUserControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<TextBlock Text="{Binding Name}"/>
</UserControl>
Person.cs
public class Person : ObservableObject
{
private int age;
private string name;
public int Age
{
get { return this.age; }
set { this.SetValue(ref this.age, value, "Age"); }
}
public string Name
{
get { return this.name; }
set { this.SetValue(ref this.name, value, "Name"); }
}
}