I have class Person:
public class Person : INotifyPropertyChanged
{
private String name = "";
public event PropertyChangedEventHandler PropertyChanged;
public Person()
{
NameProperty = "hi";
}
public Person(String _name)
{
NameProperty = _name;
}
public String NameProperty
{
get { return name; }
set
{
name = value;
OnPropertyChanged("NameProperty");
}
}
public override String ToString()
{
return NameProperty;
}
protected void OnPropertyChanged(string name)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(name));
}
}
}
And I can bind the instance of my class to TextBox:
myPerson = new Person("demas");
Binding myBinding = new Binding("NameProperty");
myBinding.Source = myPerson;
txtName.SetBinding(TextBox.TextProperty, myBinding);
Now I have collection of my class and want to bind it to ListBox:
List<Person> myCollection = new List<Person>(); // on the MainWindow level
myCollection.Add(new Person("one"));
myCollection.Add(new Person("two"));
myCollection.Add(new Person("three"));
So I have to see in the ListBox three values: one, two, three. How can I do it?
Expose your collection as a public property in your
MainWindow. If you want yourListBoxto get updated when elements are added or removed to your collection, you should use anObservableCollection<T>rather thanList<T>.Then, in your XAML, use data binding to reference the property:
Don’t forget to set the
DataContexteither on yourListBoxor on its parent window.P.S. Identifier names should identify the purpose, not the type. Use
Personsinstead ofMyCollection; useNameinstead ofNameProperty.