将对象集合绑定到ListBox

时间:2012-02-26 10:55:15

标签: c# .net wpf data-binding

我有班级人员:

    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));
            }

        }

    }

我可以将我的类的实例绑定到TextBox:

myPerson = new Person("demas");
Binding myBinding = new Binding("NameProperty");
myBinding.Source = myPerson;
txtName.SetBinding(TextBox.TextProperty, myBinding);

现在我收集了我的类,并希望将它绑定到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"));

所以我必须在ListBox中看到三个值:一,二,三。我该怎么办?

2 个答案:

答案 0 :(得分:6)

将您的收藏展示为MainWindow中的公共财产。如果您希望在向论坛添加或删除元素时更新ListBox,则应使用ObservableCollection<T>而不是List<T>

readonly ObservableCollection<Person> myCollection = new ObservableCollection<Person>();

public ObservableCollection<Person> MyCollection
{
    get { return myCollection; }
} 

然后,在您的XAML中,使用数据绑定来引用属性:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:l="clr-namespace:WpfApplication1"
        xmlns:p="clr-namespace:WpfApplication1.Properties"
        DataContext="{Binding RelativeSource={RelativeSource Self}}"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <ListBox ItemsSource="{Binding MyCollection}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding NameProperty}" />
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

不要忘记在DataContext或其父窗口上设置ListBox

P.S。标识符名称应标识目的,而不是类型。使用Persons代替MyCollection;使用Name代替NameProperty

答案 1 :(得分:3)

使用ObservableCollection而不是List。当您向集合中添加/删除项目时,这将更新UI。获得集合后,将其绑定到ListBox的ItemsSource属性。

此外,您可以通过覆盖Person类上的ToString方法或在ListBox控件上设置ItemTemplate来控制Person对象在UI上的呈现方式。

相关问题