2010-07-19 52 views
0

我试图让一个ListBox更新到ObservableCollection的内容,只要该集合中的任何内容发生更改,所以这是我为此编写的代码:Silverlight - 无法获取ListBox绑定到我的ObservableCollection

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

我设置到填充listOfUsers WCF服务呼叫:

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

ListBox永远不会填充任何东西。我认为我的问题可能与xaml有关,因为ObservableCollection实际上包含了我所有的用户。

回答

5

您错过了您的ItemsSource中的{Binding}部分。

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

而且,你可能不需要有一个DependencyProperty为您的列表,你可以实现你需要对实现INotifyPropertyChanged一类的属性是什么。这可能是一个更好的选择,除非你需要一个DependencyProperty(以及与之相伴的开销)。

例如

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

啊当然,我不能相信我忽略了这一点。非常感谢!现在完美工作 – EPatton 2010-07-19 15:11:41

相关问题