2010-07-19 51 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

相關問題