views:

247

answers:

1

I'm trying to make a ListBox that updates to the contents of an ObservableCollection whenever anything in that collection changes, so this is the code I've written for that:

xaml:

<ListBox x:Name="UserListTest" Height="300" Width="200" ItemsSource="listOfUsers">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <TextBlock Text="{Binding LastName}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox> 

C#:

public ObservableCollection<User> listOfUsers
    {
        get { return (ObservableCollection<User>)GetValue(listOfUsersProperty); }
        set { SetValue(listOfUsersProperty, value); }
    }

    public static readonly DependencyProperty listOfUsersProperty =
        DependencyProperty.Register("listOfUsers", typeof(ObservableCollection<User>), typeof(MainPage), null);

And I set up a call to a WCF Service that populates listOfUsers:

void repoService_FindAllUsersCompleted(object sender, FindAllUsersCompletedEventArgs e)
    {
        this.listOfUsers = new ObservableCollection<User>();

        foreach (User u in e.Result)
        {
            listOfUsers.Add(u);
        }

        //Making sure it got populated
        foreach (User u in listOfUsers)
        {
            MessageBox.Show(u.LastName);
        }
    }

The ListBox never populates with anything. I assume my problem may be with the xaml since the ObservableCollection actually has all of my Users in it.

+4  A: 

You're missing the {Binding} part from your ItemsSource there.

<ListBox x:Name="UserListTest" Height="300" Width="200" ItemsSource="{Binding listOfUsers}"> 
    <ListBox.ItemTemplate> 
        <DataTemplate> 
            <TextBlock Text="{Binding LastName}" /> 
        </DataTemplate> 
    </ListBox.ItemTemplate> 
</ListBox>  

Also, you may not need to have a DependencyProperty for your list, you may be able to achieve what you need with a property on a class that implements INotifyPropertyChanged. This may be a better option unless you need a DependencyProperty (and the overhead that goes along with it) for some other reason.

e.g.

public class MyViewModel : INotifyPropertyChanged
{
    private ObservableCollection<User> _listOfUsers;
    public event PropertyChangedEventHandler PropertyChanged;

    public ObservableCollection<User> ListOfUsers
    {
        get { return _listOfUsers; }
        set
        {
            if (_listOfUsers == value) return;
            _listOfUsers = value;
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("ListOfUsers"));
        }
    }

}
Steve Willcock
Ahh of course, I can't believe I overlooked that. Thanks so much! Working perfectly now
EPatton