开发者

Silverlight - Can't get ListBox to bind to my ObservableCollection

开发者 https://www.devze.com 2023-01-07 18:01 出处:网络
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:

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, Fi开发者_运维问答ndAllUsersCompletedEventArgs 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.


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

}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号